Search code examples
linkermakefileeclipse-cdt

Does order of linker flags matter when running linking step in C++?


My original question is below, but it evolved to the following related question: is there anything wrong with putting linker flags after the objects in the linker statement?


When I build in Eclipse, the following linking statement is run:

g++ -fopenmp -lconfig++ -o "pc2" ./main.o ./sampling.o ./simulation.o

which is incorrect, because lconfig++ must follow, not precede, the object file listing. So, I modified the makefile, which was automatically generated by Eclipse based on the project settings. Specifically, I changed this portion of the makefile

# Tool invocations
pc2: $(OBJS) $(USER_OBJS)
    @echo 'Building target: $@'
    @echo 'Invoking: GCC C++ Linker'
    g++ -fopenmp -lconfig++ -o "pc2" $(OBJS) $(USER_OBJS) $(LIBS)
    @echo 'Finished building target: $@'
    @echo ' '

to be as follows:

# Tool invocations
pc2: $(OBJS) $(USER_OBJS)
    @echo 'Building target: $@'
    @echo 'Invoking: GCC C++ Linker'
    g++ -o "pc2" $(OBJS) $(USER_OBJS) $(LIBS) -fopenmp -lconfig++ 
    @echo 'Finished building target: $@'
    @echo ' '

Then, after modifying that 1 line of the makefile, I entered

make clean all -C release

at the command line, which produced the following correct linking statement:

g++ -o "pc2" ./main.o ./sampling.o ./simulation.o -fopenmp -lconfig++

Therefore, I know how to fix the makefile so that the build process is correct.

What I do not know is how to configure Eclipse so that the makefile it generates places the linker flags (or "options"?) at the correct location.


Solution

  • You've answered your own question: yes, the order of objects and libraries on the link line does matter.

    is there any reason why I might need linker flags to precede the object files?

    There may well exist such linker flags. For example --start-group GNU-ld linker options must (obviously) precede the library group it starts. The --start-lib Gold linker option must (obviously) precede the objects that form a library, etc.

    I discovered that I could move ${FLAGS} in settings

    You likely have included -lconfig++ in the ${FLAGS} somewhere in Eclipse, and that's likely a mistake -- the -lconfig++ is not a linker flag (even though it looks like one), it's a library specification, and should probably be included in ${LIBS} or some such.