是否有一种方法来创建只使用所需的.o文件的makefile? [英] Is there a way to create makefile that uses only required .o files?

查看:566
本文介绍了是否有一种方法来创建只使用所需的.o文件的makefile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个可同时编译多个程序的makefile。可能有一些.cpp文件被所有的使用,和一些.cpp文件只由一个使用。目前的makefile如下:

I want to create a makefile that compiles more than one program at once. There may be some .cpp files that are used by all of them, and some .cpp files that are used by just one exclusively. The current makefile I have is following:

CPPFLAGS = -std=c++14 -MMD -pthread 
TARGETS = server.cpp client.cpp

SRC = $(wildcard *.cpp)
NON_TARGET_SRC = $(filter-out $(TARGETS),$(SRC))

all: $(TARGETS:%.cpp=%)

clean:
    rm -rf *.o
    rm -rf *.d

$(TARGETS:%.cpp=%): % : $(NON_TARGET_SRC:%.cpp=%.o) %.o ###redundant?
    g++ $(CPPFLAGS) -o $@ $^

-include $(SRC:%.cpp=%.d)

Server.cpp和client.cpp是包含main()函数的文件的名称,应该被编译为可执行文件,而不是.o文件。虽然上面的makefile工作,我认为它的工作是多余的,因为它使用所有非目标.o文件的最终编译,而它可能应该使用只有所需的(或链接器选择所需的,这样的命令的开销可以忽略不计?)。所以,问题是:

Server.cpp and client.cpp are names of files that contain main() function and are supposed to be compiled to executable, rather than .o file. While the above makefile works, I think it does work that is redundant, as it does the final compilation with using all the non-target .o files, while it probably should use only the needed ones (or does the linker pick the needed ones on itself, making such a command's overhead negligible?). So, the question is:

有没有办法列出特定程序需要的.o文件?

编辑:

以下代码似乎工作正常,感谢将所有目标文件打包一个库文件。

The following code seems to work just fine, thanks to packing all the object files into one library file.

CPPFLAGS = -std=c++14 -MMD -pthread 
TARGETS = server.cpp client.cpp

LIBRARY_NAME=objects
LIBRARY_FILE=lib$(LIBRARY_NAME).a
SRC = $(wildcard *.cpp)
NON_TARGET_SRC = $(filter-out $(TARGETS),$(SRC))
LDFLAGS = -L.
LDLIBS = -l$(LIBRARY_NAME)

all: $(TARGETS:%.cpp=%)

clean:
    rm -rf *.o
    rm -rf *.d
    rm -rf *.a

$(TARGETS:%.cpp=%): % : $(LIBRARY_FILE) %.o
    g++ $(CPPFLAGS) -o $@ $*.o $(LDFLAGS) $(LDLIBS)

$(LIBRARY_FILE): $(NON_TARGET_SRC:%.cpp=%.o)
    ar rcu $@ $(NON_TARGET_SRC:%.cpp=%.o)
    ranlib $@

-include $(SRC:%.cpp=%.d)


推荐答案

这样做的方法是构建所有的目标文件将 main()函数插入库并与库链接。建立一个库是这样的:

The way to do that is to build all object files except those with a main() function into a library and link with the library. Building a library is something like this:

libfoo.a: $(LIBOFILES)
    ar rcu $@ $(LIBOFILES)
    ranlib $@

然后,您还应将Makefile设置为使用库:

You'd then also set the Makefile to use the library:

LDFLAGS = -L.
LDLIBS  = -lfoo

这篇关于是否有一种方法来创建只使用所需的.o文件的makefile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆