Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking objects and static libraries

I am having a hard time figuring out what flags to pass to g++ when performing linking. Basically, I compile some code with these "standard" flags:

CXXFLAGS = -Wall -Wextra -Wconversion -pedantic -std=c++0x -O2

and, afterwards, I merge the produced .o files into several static libraries like so:

libxxx.a: xxx1.o xxx2.o ...
    ar rcs $@ $^
libyyy.a: yyy1.o yyy2.o ...
    ar rcs $@ $^
...

Questions:

  • Do I need to use the -static flag in CXXFLAGS when compiling the .o files?

After the static libraries are created, I want to link some compiled .o files together with some of these libraries in order to build an executable so I use this:

LINKER = g++
LIB_DIR = lib/linux
SYSTEM_LIBS = -lgmp
LDFLAGS = -Wall -L $(OUTPUT_DIR) -L $(LIB_DIR) $(SYSTEM_LIBS)
$(LINKER) $^ $(LDFLAGS) -lsvm -lUtils -lKinderedSpirits -o $@

exe:
    $(LINKER) o1.o o2.o $(LDFLAGS) -lxxx -lyyy -lzzz -o $@

Questions:

- Should I use the -static flag here? - Does -Wall make any sense here or is it useful just for compiling? - Are there any other "standard" flags that need to be passed to the linker, similar to the ones recommended for the compiler?

Also, during linking it's giving me exceptions about undefined references from the GMP library. As far as I can tell, -lgmp is sent to the linker and it is installed on the system (I was able to compile a simple hello world which uses GMP from the command line) and libxxx.a libyyy.a libzzz.a are located in $(LIB_DIR). Maybe I should mention that the GMP symbols are used in libxxx.a.


UPDATE:

I managed to fix the undefined references for the GMP symbols. The issue was caused by the order in which I placed the libraries. Basically, as specified here, I need to reference the libraries that depend on GMP before -lgmp. Anyway, I'm still looking for answers to my 3 questions above.

like image 405
Mihai Todor Avatar asked Nov 03 '22 21:11

Mihai Todor


1 Answers

Q: Should I also use the -static flag here? A: Probably not necessary. This flag just makes it impossible to accidentally link in dynamic libraries.

Q: Does -Wall make any sense here or is it useful just for compiling? A: I believe it's just for compiling. (fyi, the capital W followed by the word "all" species you want all warnings during compilation)

Q: Are there any other "standard" flags that need to be passed to the linker, similar to the ones recommended for the compiler? A: Not that I'm aware of. You can find common options here: http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html

Are you running into any specific error you'd care to paste?

like image 89
loki11 Avatar answered Nov 09 '22 14:11

loki11