Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default linker setting in Makefile for linking C++ object files

Tags:

makefile

Consider this Makefile

% cat Makefile main: main.o add.o 

which uses cc instead of g++ to link the object files

% make g++ -Wall -pedantic -std=c++0x   -c -o main.o main.cpp g++ -Wall -pedantic -std=c++0x   -c -o add.o add.cpp cc   main.o add.o   -o main main.o:main.cpp:(.text+0x40): undefined reference to `std::cout' ... 

How do I tell (GNU) Make to use g++ (which links the C++ libraries) instead of cc?

like image 632
Micha Wiedenmann Avatar asked Nov 14 '12 08:11

Micha Wiedenmann


People also ask

What is linker in makefile?

A makefile is a set of instructions used by make . They can be instructions that build a program, install some files, or whatever you want make to do. A linker is a program that takes object files as input and combines them into an output executable (or shared library).

Which linker does GCC use?

GCC uses a separate linker program (called ld.exe ) to perform the linking.


1 Answers

(GNU) Make has built-in rules, which is nice, because it is enough to give dependencies without rules:

main: main.o add.o     # no rule, therefore use built-in rule 

However the build-in rule in this case uses $(CC) for linking object files.

% make -p -f/dev/null ... LINK.o = $(CC) $(LDFLAGS) $(TARGET_ARCH) ... LINK.cc = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH) ... %: %.o #  recipe to execute (built-in):         $(LINK.o) $^ $(LOADLIBES) $(LDLIBS) -o $@ 

To let Make chose the correct linker, it is sufficient to set LINK.o to LINK.cc. A minimal Makefile can therefore look like

% cat Makefile LINK.o = $(LINK.cc) CXXFLAGS=-Wall -pedantic -std=c++0x  main: main.o add.o 
like image 92
Micha Wiedenmann Avatar answered Sep 18 '22 21:09

Micha Wiedenmann