简体   繁体   中英

Linking in a static library failes, but linking a shared library succeeds

I can build my application against the shared library but I'm getting the unresolved symbol errors when linking it against the static version of the same library:

I can build my application this way:

g++ -lutils application.cpp -o application.exe

The above command links in the shared version of an utils library.

I'm trying link against the static version of the library like this:

g++ -l:utils.a application.cpp -o application.exe

Both times I'm using

export LD_LIBRARY_PATH=path/to/utils:$LD_LIBRARY_PATH

to inform g++ where utils.a is placed.

The unresolved symbol reported by ld is present in the output of the nm:

nm --defined-only path/to/utils.a

and is marked with the "T" (meaning that it is from the code section).

I'm trying to figure out what can be the reason of the problem.

Is it correct to use LD_LIBRARY_PATH to specify where to search for utils.a?

What is the exact command to verify that a static library defines (resolves) the symbol? Is the command

nm --defined-only path/to/utils.a

enough or should I use any additional options like

nm --defined-only --demangle path/to/utils.a

eg?

Just option -static should be enough for compiler. In case only one library has to be static, then -static- and lib name is short name not file name.

Is it correct to use LD_LIBRARY_PATH to specify where to search for utils.a?

  1. As mentioned by @user10605163, LD_LIBRARY_PATH is not to find path to static library at compile and link time. It is an environment variable used in some Linux distribution to search shared libraries during run time. Please find more documentation here It is useful for build and test environment but not a recommended way of linking in production systems.

What is the exact command to verify that a static library defines (resolves) the symbol? Is the command nm --defined-only path/to/utils.a

  1. Yes, that is correct. However based on the information provided this error is not likely an error with symbols not present in utils(as it worked with shared library), but with the linking.

Refer GNU documentation GCC link options Excerpt:

-l library : Search the library named library when linking. The linker searches a standard list of directories for the library. The directories searched include several standard system directories plus any that you specify with -L.

Also, with -l link option you need to provide the library name (without 'lib' and extension) or full file name. -lutils or -llibutils.a You can also provide direct full path here only, if required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM