Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

c++ - linker option to list libraries used

I am working on a Linux platform and using the GNU C++ compiler. I am trying to resolve a link error that says some symbols are undefined. I can go find libraries with the name provided on the command line, and see that they contain the symbols in question ( using the 'nm' utility ).

I know that for the compilation step, I can use the command-line flag '-H' instead of '-c' in order to get a list of header files that were #included into the compilation. Is there a similar option for the linker? I figure if I could see the list of files that the linker used to handle each '-lmylibrary' flag, I can troubleshoot further.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you get an undefined symbol error it means you forgot to link some library, knowing which libraries you link to will probably not be as useful as you may think, because obviously the symbol is missing from those libraries, however you can use the -print-file-name=library option to find out which path gcc would use to link a library, example:

$ gcc -print-file-name=libc.a
/usr/lib/x86_64-linux-gnu/gcc/x86_64-linux-gnu/4.5.2/../../../libc.a

Also passing --trace to the linker shows a similar output

gcc -Wl,--trace myprog.c -o myprog -L. -lmylib
-lmylib (./libmylib.a)
-lgcc_s (/usr/lib/x86_64-linux-gnu/gcc/x86_64-linux-gnu/4.5.2/libgcc_s.so)
....

(Note in the above that --trace is an argument to the linker so it goes in -Wl. gcc invoked for linking won't emit anything useful for --trace as an argument to gcc its self).

You could also use ldd after you successfully build the program to find out which dynamically linked libraries were used, its output looks like this:

ldd `which ls`
linux-vdso.so.1 =>  (0x00007fff7ffff000)
libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007f2e8ea93000)
librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007f2e8e88b000)
libacl.so.1 => /lib/x86_64-linux-gnu/libacl.so.1 (0x00007f2e8e682000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f2e8e2ee000)
....

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...