简体   繁体   English

如何为带有.h文件的几个.cpp文件和不带有.h的main.cpp创建一个makefile

[英]How to create a makefile for several .cpp files with .h files and main.cpp without a .h

I have: 我有:

main.cpp 
distance.cpp
distance.h
adjacencyList.cpp
adjacencyList.h

Here is my makefile: 这是我的makefile:

all: distance main adjacencyList
    g++ distance.o main.o adjacencyList.o

main.o: main.cpp
    g++ main.cpp -lstdc++

adjacencyList.o: adjacencyList.cpp
    g++ adjacencyList.cpp -lstdc++

distance.o: distance.cpp
    g++ distance.cpp -lstdc++

clean:
    rm -rf *.o all

I am getting this error. 我收到此错误。 So I'm pretty sure I'm doing something wrong with main because it is not a class like the other two and does not have a .h file. 因此,我很确定自己对main的处理有问题,因为它不是其他两个类,并且没有.h文件。

在此处输入图片说明

Update: 更新:

After trying Ben Voigt's solution I am getting 1 error: 在尝试Ben Voigt的解决方案后,我得到1错误:

在此处输入图片说明

Your rules to create object files are missing the -c option, for "compile only". 您创建目标文件的规则缺少-c选项,用于“仅编译”。 So they are trying to link, and failing because there is no main() . 因此他们正在尝试链接,但由于没有main()而失败。

Then, your all target names an executable for each of the compilation units. 然后, all目标为每个编译单元命名一个可执行文件。 Again, that's wrong because they don't all have main() . 同样,这是错误的,因为它们都没有main() You should have only one executable. 您应该只有一个可执行文件。 all should also be configured as a phony target, because it doesn't build an actual file named all . all还应该配置为phony目标,因为它不会构建名为all的实际文件。

All your rules are failing to control the name of the output file. 您的所有规则都无法控制输出文件的名称。

All your rules are failing to pass flags. 您的所有规则均未通过标记。

Your rules are missing dependencies on the headers, so editing headers won't cause the right files to be recompiled. 您的规则缺少对标头的依赖性,因此编辑标头不会导致正确的文件重新编译。

Really, you should get rid of the compile and link rules and let make use its built-in ones. 确实,您应该摆脱编译和链接规则,而make使用其内置规则。 Focus on your build targets and dependencies. 专注于您的构建目标和依赖项。

Your end makefile should look something like this (of course, using spaces not tabs) 您的最终makefile应该看起来像这样(当然,使用空格而不是制表符)

all : main

.PHONY : all clean

CC = g++
LD = g++

main : main.o adjacencyList.o distance.o

main.o: main.cpp adjacencyList.h distance.h

adjacencyList.o: adjacencyList.cpp adjacencyList.h

distance.o: distance.cpp distance.h

clean:
    rm -rf *.o main

Wild guess: it is possible you are missing a semi-colon somewhere before including adjacencyList.h. 大胆的猜测:在包含adjacencyList.h之前,您可能在某个地方缺少分号。 Check each header files and make sure each class definition is properly terminated with a semi-colon 检查每个头文件,并确保每个类定义均以分号正确终止

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM