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

use*_*285 0 c++ gcc

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

g++ test1 -o run1
g++ test2 -o run2
...
Run Code Online (Sandbox Code Playgroud)

如果.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
Run Code Online (Sandbox Code Playgroud)

Gal*_*lik 9

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

all: test1 test2
Run Code Online (Sandbox Code Playgroud)

这将转方案test1.cpp,并test2.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)
Run Code Online (Sandbox Code Playgroud)

注意:目标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)
Run Code Online (Sandbox Code Playgroud)

注意: $@仅表示输出程序文件名(test1),$^表示列出的所有输入文件(prog1.cpp prog2.cpp在本例中).