user8680580
user8680580

Reputation:

the correct usage of `LDFLAGS` in makefile

First, the makefile in question roughly looks like this (I'm writing off my memory):

CXX=g++
CXXFLAGS=-c -Wall -std=c++11 -O3
LDFLAGS=-Wall -std=c++11 -O3

all: clean car.out

clean:
    rm -f *.o *.out


car.out: a.o b.o
    $(CXX) -o $@ $(LDFLAGS) $^

a.o: a.cpp
    $(CXX) $(CXXFLAGS) $<

b.o: b.cpp
    $(CXX) $(CXXFLAGS) $<

Basically this will make some object files first and then link them together. I think this is semantically unreasonable because:

  1. As its name suggests, LDFLAGS is for ld, but there is no flags for it here. If we need some external library like OpenGL, then a flag like -LGL is passed to g++, and then g++ would pass it to the linker. In that case, it would be reasonable to put -LGL in LDFLAGS.

  2. Even if it's the case where we put flags such as -Wall into LDFLAGS, it doesn't make much sense. This kind of flags are intuitively for the compilation process, not linking (unless I understand this process wrong).

  3. In https://www.gnu.org/software/make/manual/html_node/Implicit-Variables.html, there is a piece of code $(CC) -c $(CFLAGS) $(CPPFLAGS), which passes -c explicitly. I think this is the better way to do this--putting all compilation flags (e.g. -Wall) into CXXFLAGS, and pass in -c explicitly for object file compilation. Of course, the web page does not say that this piece of code is definitely better or the only way to do it.

So the only reason I can think of to use LDFLAGS there is because "there's a linking step," which doesn't make much sense to me. In my opinion, the makefile above should look like:

CXX=g++
CXXFLAGS=-Wall -std=c++11 -O3

all: clean car.out

clean:
    rm -f *.o *.out


car.out: a.o b.o
    $(CXX) -o $@ $(LDFLAGS) $^

a.o: a.cpp
    $(CXX) -c $(CXXFLAGS) $<

b.o: b.cpp
    $(CXX) -c $(CXXFLAGS) $<

LDFLAGS defaults to an empty string, so we can still have it there for the linking step.

However I'm not sure if I'm right.

Upvotes: 3

Views: 8104

Answers (1)

xhienne
xhienne

Reputation: 6134

You are right that compilation flags have nothing to do in LDFLAGS. Just define LDFLAGS explicitly so that another editor -or yourself, when some time has passed- can figure out at a glance that 1. it is empty and 2. where to modify it (like adding -s to it, which is quite common).

Upvotes: 1

Related Questions