创建makefile时遇到麻烦

时间:2016-11-04 18:16:58

标签: makefile clang++

出于某种原因,我总是在创建makefile时遇到问题。在这种情况下,我使用clang ++和-std = c ++ 11。 我有一个可执行的Carbuyer.cpp依赖于CarFactory(.cpp和.h),而CarFactory又依赖于Car(.cpp和.h)

我当前的尝试看起来像这样:

CarBuyer: CarBuyer.cpp CarFactory Car
    clang++ -std=c++11 -v -o CarBuyer CarBuyer.cpp CarFactory Car
Car: Car.cpp Car.h
    clang++ -std=c++11 Car.cpp Car.h
CarFactory: CarFactory.cpp CarFactory.h
    clang++ -std=c++11 CarFactory CarFactory.cpp CarFactory.h 
clean:
    rm -f core CarBuyer 

但是我在编译时遇到了来自CarFactory的未定义函数错误:

clang++ -std=c++11 CarFactory.cpp CarFactory.h 
clang: warning: treating 'c-header' input as 'c++-header' when in C++ mode,
     this behavior is deprecated
/usr/bin/../lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o: In
    function `_start':
(.text+0x20): undefined reference to `main'
/tmp/CarFactory-13dbb4.o: In function `FordFactory::makeCar()':
CarFactory.cpp:(.text+0x5a): undefined reference to `Ford::Ford()'
/tmp/CarFactory-13dbb4.o: In function `ToyotaFactory::makeCar()':
CarFactory.cpp:(.text+0xba): undefined reference to `Toyota::Toyota()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [CarFactory] Error 1

代码在VS2015中编译得很好,但在用clang ++编译时没有编译,导致我相信我的错误在Makefile中。

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

首先,您需要告诉编译器使用-c选项进行编译。

其次,必须定义输出文件:使用-o file或更好-o $@

CarBuyer: CarBuyer.o CarFactory.o Car.o
    clang++ -std=c++11 -o $@ CarBuyer.o CarFactory.o Car.o

CarBuyer.o: CarBuyer.cpp
    clang++ -std=c++11 -c -o $@ CarBuyer.cpp

Car.o: Car.cpp Car.h
    clang++ -std=c++11 -c -o $@ Car.cpp Car.h

CarFactory.o: CarFactory.cpp CarFactory.h
    clang++ -std=c++11 -c -o $@ CarFactory.cpp CarFactory.h 

clean:
    rm -f core CarBuyer *.o

将头文件放入编译规则是非常不寻常的,如果可以的话,给它一个检查并从clang ++命令行中禁止它们。