Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ways to specify libraries to gcc/g++

I'd be curious to understand if there's any substantial difference in specifying libraries (both shared and static) to gcc/g++ in the two following ways (CC can be g++ or gcc)

CC -o output_executable /path/to/my/libstatic.a /path/to/my/libshared.so source1.cpp source2.cpp ... sourceN.cpp

vs

CC -o output_executable -L/path/to/my/libs -lstatic -lshared source1.cpp source2.cpp ... sourceN.cpp

I can only see a major difference being that passing directly the fully-specified library name would make for a greater control in choosing static or dynamic versions, but I suspect there's something else going on that can have side effects on how the executable is built or will behave at runtime, am I right?

Andrea.

like image 383
abigagli Avatar asked Mar 29 '10 10:03

abigagli


People also ask

Which gcc option is used to specify the library?

The -l option tells gcc to link in the specified library.

What option should be added to a gcc command in order to link in functions from a library?

Short answer: If you want to use functions from the math library in C, it's not enough to put #include<math. h> at the top of your source code. In addition, you must add the - lm flag to the gcc compiler command in order to use math functions in your C code.

How do I link a shared library in Makefile?

As already mentioned here, the thing you probably want is the linker option -rpath . Like that, you can set a default search path for the binary. Looks like you even already use -rpath in your makefile, but you specify the wrong path: LIBS = -L$(LIB) -lfuse -lsqlite3 -lkw_taglib -ltag_c -ltag -Wl,-rpath=.


1 Answers

Ok, I can answer myself basing on some experiments and a deeper reading of gcc documentation:

From gcc documentation: http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html

[...] The linker handles an archive file by scanning through it for members which define symbols that have so far been referenced but not defined. But if the file that is found is an ordinary object file, it is linked in the usual fashion. The only difference between using an -l option and specifying a file name is that -l surrounds library with lib' and.a' and searches several directories

This actually answers also to the related doubt about the 3rd option of directly specifying object files on the gcc command line (i.e. in that case all the code in the object files will become part of the final executable, while using archives, only the object files that are really needed will be pulled in).

like image 156
abigagli Avatar answered Sep 24 '22 15:09

abigagli