我的项目总是包含:
成对的Foo.h和Foo.cpp
一些额外的标题util.h等。
编写
的makefile的最简单方法是什么奔跑
$CC -c foo.cpp
对于每个.cpp文件,保持对其相应的.h文件的依赖
我使用Linux(Ubuntu)和gcc / g ++。
答案 0 :(得分:3)
请使用automake
。您将获得正确的依赖关系跟踪,符合GNU Makefile Standards的makefile(例如,make install
做正确的事情并尊重DESTDIR
和prefix
),检查的能力根据需要系统怪癖,并支持构建适当的分发tarball。
这是一个最小的configure.ac
:
-*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
AC_PREREQ([2.61])
AC_INIT([FULL-PACKAGE-NAME], [VERSION], [BUG-REPORT-ADDRESS])
AM_INIT_AUTOMAKE([foreign])
# Checks for programs.
AC_PROG_CXX
# Checks for libraries.
# Checks for header files.
# Checks for typedefs, structures, and compiler characteristics.
# Checks for library functions.
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
和最小Makefile.am
:
## Process this file with automake to generate Makefile.in
bin_PROGRAMS = foo
foo_SOURCES = foo.cpp bar.h baz.h quux.cpp
运行autoreconf -i
以生成配置脚本,然后运行./configure
和make
。
答案 1 :(得分:2)
也许您可以查看CMake?
如果您不熟悉CMake,它基本上是一个Makefile生成器(或XCode,或Visual Studio Projects等,具体取决于平台),因此它允许您只指定所需的变量,并处理标头依赖性问题为你,makefile生成等。
答案 2 :(得分:1)
这个怎么样:
%.o: %.cpp %.h
$(CC) -c $< -o $@
# Some things have extra dependencies. (Headers like util.h are unlikely
# to change, but you can handle them this way if you really want to.)
#
# foo.o and bar.o both depend on baz.h
foo.o bar.o: baz.h
# foo.o also depends on gab.h and jig.h
foo.o: gab.h jig.h
# You will need a list of object files. You can build it by hand:
OBJ_FILES = foo.o bar.o snaz.o # and so on
# ...or just grab all the files in the source directory:
SOURCE_FILES = $(wildcard *.cpp)
OBJ_FILES = $(SOURCE_FILES:.cpp=.o)
# It is possible to get this from the environment, but not advisable.
LIBS = -lred -lblue
final-thing: $(OBJ_FILES)
$(CC) $(LIBS) $^ -o $@
答案 3 :(得分:1)
这是一个简单的shell脚本,它从给定目录中的所有.cpp文件构造一个makefile:
# !sh
if [ $# = 0 ]
then
echo -e "please give executable name"
exit 1
fi
echo -e -n "CC=g++\nOPTIMS=\nLIBS= " > makefile
echo >> makefile
echo -n "$1: " >> makefile
for fic in *.cpp
do
echo -n "${fic%\.cpp}.o " >> makefile
done
echo >> makefile
echo -n -e "\t\$(CC) " >> makefile
for fic in *.cpp
do
echo -n "${fic%\.cpp}.o " >> makefile
done
echo -n -e "-o $1 \$(OPTIMS) \$(LIBS)\n" >> makefile
echo >> makefile
for fic in *.cpp
do
g++ -MM $fic >> makefile
echo -e "\t\$(CC) -c $fic \$(OPTIMS)\n" >> makefile
done
exit 0
它使用gcc的-MM
选项来创建makefile依赖项。只需在sources目录中创建脚本(让我们称之为micmake
),使其可执行(chmod +x micmake
)并输入
./micmake go
它将创建一个makefile,make
命令可以编译你的项目。可执行文件名为go
。如果需要特殊的编译选项或库,可以编辑makefile。对于更复杂的项目和依赖项,您应该使用automake,cmake或scons。
答案 4 :(得分:0)
答案 5 :(得分:0)
以下是我的某个项目的示例 - 您只需将新对foo1.cc
和foo1.h
放入其中,它们就会自动为您构建:
# determine all sources and from that all targets
sources := $(wildcard *.cpp)
programs := $(sources:.cpp=)
## compiler etc settings used in default make rules
CXX := g++
CPPFLAGS := -Wall
CXXFLAGS := -O3 -pipe
LDLIBS :=
# build all and strip programs afterwards
all: $(programs)
@test -x /usr/bin/strip && strip $^