如何一次编译多个独立的CPP文件?

时间:2015-03-04 17:11:37

标签: c++ gcc

我不是在询问makefile。我有多个.cpp文件用于测试目的。所以在终端,我需要写:

g++ test1 -o run1
g++ test2 -o run2
...

如果.cpp文件被更改,那么我将不得不再次运行上述命令。这种情况有解决方案吗?谢谢!

我认为makefile无法实现这一目标。这就是我以这种方式提出要求的原因。我将完整地保留上述问题。下面是我的makefile,我应该如何为多个文件更改它?

GCC=g++
GFLAGS=-Wall -g -std=c++11 -O3 
SRC=./test1.cpp    
OUT= test1.out    

g:
    $(GCC) $(GFLAGS) $(SRC) -o $(OUT)

clean:
    rm -rf $(OUT) ./*~ ./*.o

3 个答案:

答案 0 :(得分:8)

我知道你不是在询问Makefile,但对于你所描述的场景,makefile可以像这样简单(使用GNU Make):

all: test1 test2

这会将程序test1.cpptest2.cpp转换为可执行文件test1test2

修正后的问题

已添加说明

如果您希望能够设置编译器和标志,那么您可以使用编译器的变量CXX和编译器标志的CXXFLAGS来执行此操作:

CXX := g++ # set the compiler here
CXXFLAGS := -Wall -Wextra -pedantic-errors -g -std=c++11 -O3 # flags...
LDFLAGS := # add any library linking flags here...

# List the programs in a variable so adding
# new programs is easier
PROGRAMS := test1 test2

all: $(PROGRAMS)

# no need to  write specific rules for
# your simple case where every program
# has a corresponding source code file
# of the same name and one file per program.

clean:
    rm -f *.o $(PROGRAMS)

注意:目标all:是默认目标,当您在没有参数的情况下键入make时,它就会运行。

最终示例:其中一个程序需要两个输入源文件,因此需要一个特殊规则。另一个文件仍然会像前面的示例一样自动编译。

CXX := g++ # set the compiler here
CXXFLAGS := -Wall -Wextra -pedantic-errors -g -std=c++11 -O3 # flags...

# List the programs in a variable so adding
# new programs is easier
PROGRAMS := test1 test2

all: $(PROGRAMS)

# If your source code filename is different
# from the output program name or if you
# want to have several different source code
# files compiled into one output program file
# then you can add a specific rule for that 
# program

test1: prog1.cpp prog2.cpp # two source files make one program
    $(CXX) $(CXXFLAGS) -o $@ $^ $(LDFLAGS)

clean:
    rm -f *.o $(PROGRAMS)

注意: $@仅表示输出程序文件名(test1),$^表示列出的所有输入文件(prog1.cpp prog2.cpp in这种情况)。

答案 1 :(得分:1)

如果您坚持不使用Make,则可以将所有命令写入纯文本文件并将其作为shell脚本执行。

答案 2 :(得分:0)

编辑我感到压力很大,OP希望将多个文件编译成一个二进制文件,而不是多个文件中的多个二进制文件。


做这样的事情:

g++ file1.cpp file2.cpp -o binary

相关问题