The Linux dynamic library shares the global variables of the main program!

When I first started developing, all the code was together;

Later, I wanted to separate some basic functions and make so;

But because there is no separation at the beginning, the result: the function that you want to separate uses a lot of global variables; there is no problem in compiling so, but there is a problem when the main program loads so, and the variable symbol cannot be found.

Various searches were fruitless, and finally found:

On linux, when linking the main program, use the parameters -Wl,--export-dynamic

On AIX, use 'deferred imports' and enable 'runtime linking'.

Add: -Wl,--export-dynamic when the main program is compiled; the problem is solved.

Load so code:

if((handle = dlopen(file_name, RTLD_NOW)) == NULL) {
		printf("[LibAes] dlopen error - %s\n", dlerror());
		return NULL;
	}

principle:

Use of the "--export-dynamic" parameter

GCC can use the -Wl, --export-dynamic parameter when compiling an executable file. At this time, the linker will .

gcc -Wl,--export-dynamic -o p1 p1.c -L. -l0

If you create a dynamically linked executable without the -Wl,--export-dynamic option, the dynamic symbols it exports include only those used by dynamic objects at link time. Because dlopen loads the dynamic library by itself, there is no process of dynamic symbol resolution with the executable file , so if the dynamic library loaded by dlopen uses the functions defined in the main module, the symbol cannot be found.

When the default linker generates an executable file, it will only put those symbols that are referenced by other shared modules at the time of linking into the dynamic symbol table, which can reduce the size of the dynamic symbol table, that is, reverse in the shared module. When referencing symbols in the main module, only those symbols referenced by the shared module at link time are exported. (The main module of the shared module that depends on the symbol table of the main module will be linked, otherwise it will not be linked, and the symbols of the main module referenced by the unlinked module will not be exported to the dynamic symbol table, resulting in an error at runtime. ).

However, after using the --export-dynamic parameter, the executable program will become larger because all global symbols are exported to the dynamic symbol table.

================

In turn, the main program wants to use the global variables of the dynamic library. I tried it a little, but it didn't work!

No matter, now I'm very satisfied!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324772917&siteId=291194637