Where to put things (CFLAGS or CXXFLAGS) on Makefile?

折月煮酒 提交于 2019-12-10 18:02:20

问题


First the Makefile here had

CFLAGS   = -g -Wall -lm

I was playing with C that time. Now I'm on C++ and I have to add -I eigen, quick google on it and found CXXFLAGS exist for the C++ world, while CFLAGS exist for the C world. So I updated Makefile to

CFLAGS   = -g -Wall -lm
CXXFLAGS = -I eigen

Then I found https://wiki.gentoo.org/wiki/GCC_optimization, and was inspired to updated it again

CFLAGS   = -g -Wall -lm
CXXFLAGS = ${CFLAGS} -I eigen

The complete thing:

CC       = g++
CFLAGS   = -g -Wall -lm
CXXFLAGS = ${CFLAGS} -I eigen
OBJS     = main.o multiply.o 
PROGRAM  = multitply
$(PROGRAM): $(OBJS)
    $(CC) $(OBJS) $(CFLAGS) -o $(PROGRAM)

Should I add -I eigen to CXXFLAGS or CFLAGS?

Also noticed the existence of CPPFLAGS.

Should I change to $(CC) $(OBJS) $(CXXFLAGS) $(CPPFLAGS) -o $(PROGRAM) or to $(CC) $(OBJS) -o $(PROGRAM)?

Should I change to $(PROGRAM): $(OBJS) *.h, so it rebuilds whenever .h files get changes?

Any other improvements to it?


回答1:


I would use CFLAGS when compiling C files and CXXFLAGS when compiling C++ files. Besides CFLAGS and CXXFLAGS you are perhaps missing another relevant variable here: CPPFLAGS.

Should I add -I eigen to CXXFLAGS or CFLAGS?

CPPFLAGS is typically used for providing options related to the preprocessor. I would use this variable for specifying include directories:

CPPFLAGS = -I eigen

Another interesting variable, which is useful for providing libraries, would be LDLIBS. You could take advantage of it for passing -lm:

LDLIBS = -lm

Should I change to $(PROGRAM): $(OBJS) *.h, so it rebuilds whenever .h files get changes?

The approach I would recommend is to add prerequisites for the header files to the corresponding object files by writing rules without recipe, for example:

main.o: main.h multiply.h ...
multiply.o: multiply.h ...

Besides, * won't do what you expect to do, i.e., it is not a wildcard in that context. Place those lines at the end of the Makefile, so that they don't replace the default target.


The Makefile could be something like:

CXXFLAGS = -g -Wall
CPPFLAGS = -I eigen
LDLIBS   = -lm
OBJS     = main.o multiply.o 
PROGRAM  = multitply

$(PROGRAM): $(OBJS)
   $(CXX) $^ $(LDLIBS) -o $@

No need for repeating $(PROGRAM) and $(OBJS) in the recipe, you can simply use the automatic variables $@ and $^, respectively.



来源:https://stackoverflow.com/questions/50783479/where-to-put-things-cflags-or-cxxflags-on-makefile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!