[英]Makefile for compiling a number of .cpp and .h into a lib
我在 Cygwin 下使用 gcc/g++ 运行 Windows 7。 用于将一组 .cpp(C++ 源代码)和 .h(头文件)文件编译为静态库 (.dll) 的 Makefile 格式(和扩展名,我认为是 .mk?)是什么。 假设我有一组可变的文件:
文件1.h
文件2.cpp
文件2.h
文件3.cpp
文件3.h
....
将这些编译成静态库的 makefile 格式(和扩展名)是什么? (我对 makefile 很陌生)最快的方法是什么?
扩展名完全没有,如果您希望 GNU make 自动找到该文件,则该文件称为Makefile
(或makefile
)。
至少,GNU make 允许您依赖某些自动变量,这些变量本身就可以让您控制使用 C/C++ 文件作为输入的大部分构建过程。 这些变量包括CC
、 CPP
、 CFLAGS
、 CPPFLAGS
、 CXX
、 CXXFLAGS
和LDFLAGS
。 这些控制开关的C / C ++预处理器,编译器和链接器(即产生所谓的“可执行程序”,或在plainspeak“程序正在编译”程序) make
将使用。
GNU make 还包含许多隐式规则,旨在使其能够从 C/C++ 源代码自动构建程序,因此您不必[总是] 编写自己的规则。
例如,即使没有makefile,如果您尝试运行make foobar
,GNU make 将尝试首先从foobar.c
或foobar.cpp
构建foobar.o
(如果找到),通过调用适当的编译器,然后将尝试构建foobar
通过从系统库和foobar.o
组装(包括链接)它的部分。 简而言之,即使没有 makefile,GNU Make 也知道如何构建foobar
程序——这要归功于隐式规则。 您可以通过使用-p
开关调用make
来查看这些规则。
有些人喜欢依靠 GNU make 的隐式规则数据库来拥有精简和简短的 makefile,其中只指定了特定于他们项目的文件,而有些人可能会禁用整个隐式规则数据库(使用-r
开关)和通过指定 makefile 中的所有内容,可以完全控制构建过程。 我不会评论这两种策略的有效性,但请放心,两者都在某种程度上起作用。
在构建 dll 时,您可以设置很多选项,但如果您从命令行执行此操作,则可以使用以下基本命令:
gcc -shared -o mydll.dll file1.o file2.o file3.o
这是一个将处理整个构建过程的 makefile(通常称为Makefile
):
# You will have to modify this line to list the actual files you use.
# You could set it to use all the "fileN" files that you have,
# but that's dangerous for a beginner.
FILES = file1 file2 file3
OBJECTS = $(addsuffix .o,$(FILES)) # This is "file1.o file2.o..."
# This is the rule it uses to assemble file1.o, file2.o... into mydll.dll
mydll.dll: $(OBJECTS)
gcc -shared $^ -o $@ # The whitespace at the beginning of this line is a TAB.
# This is the rule it uses to compile fileN.cpp and fileN.h into fileN.o
$(OBJECTS): %.o : %.cpp %.h
g++ -c $< -o $@ # Again, a TAB at the beginning.
现在要构建mydll.dll
,只需键入“make”。
一些注意事项。 如果您只键入“make”而不指定 makefile 或目标(要构建的东西),Make 将尝试使用默认的 makefile(“GNUMakefile”、“makefile”或“Makefile”)和默认目标(第一个一个在 makefile 中,在本例中为mydll.dll
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.