[英]Can I include a cpp file in the main when there is a hpp?
For example: I have a class called A. And there is:例如:我有一个名为 A 的类。并且有:
A.hpp
A.cpp
main.cpp
for my project为我的项目
By default, I only need to include A.hpp in the main so I can compile it, either using IDE such as Xcode or using:默认情况下,我只需要在 main 中包含 A.hpp,这样我就可以编译它,使用 IDE(例如 Xcode)或使用:
g++ main.cpp A.cpp -o xxxxx
But the submission system only allows me to use:但是提交系统只允许我使用:
g++ main.cpp -o xxxx
I tried to include A.cpp in the main, but the IDE says: main file cannot be included recursively when building a preamble我试图在 main 中包含 A.cpp,但 IDE 说:构建序言时不能递归包含主文件
Is there any solution?有什么解决办法吗? I want to keep my hpp and cpp separately.我想分别保留我的 hpp 和 cpp。
Can I include a cpp file我可以包含一个 cpp 文件吗
In theory, any file can be included.理论上,可以包含任何文件。
But as a convention, you should never include cpp files.但作为惯例,您永远不应该包含 cpp 文件。
But the submission system only allows me to use:但是提交系统只允许我使用:
g++ main.cpp -o xxxx
If you cannot compile A.cpp then don't write such file at all.如果你不能编译 A.cpp 那么就不要写这样的文件。 Write the definitions that you would have written in A.cpp into main.cpp instead.将您在 A.cpp 中编写的定义写入 main.cpp。 This achieves the same as including with a macro, but there won't be duplicate definitions in another cpp file.这与使用宏包含的效果相同,但在另一个 cpp 文件中不会有重复的定义。
You can #include
any file you want.你可以#include
任何你想要的文件。 #include
is automatic copy-paste. #include
是自动复制粘贴。 It looks in the file you tell it to include, and it reads whatever's in the file, and it pretends you wrote that in your original file.它查看您告诉它包含的文件,并读取文件中的任何内容,并假装您将其写入原始文件中。 It doesn't care what's in the file, it just does that.它不关心文件中的内容,它只是这样做。 You can include a .h
file, a .hpp
file, a .cpp
file, a .txt
file, a .py
file, a .jpg
file, or anything you want, as long as it's got valid C++ code in it.您可以包含一个.h
文件、一个.hpp
文件、一个.cpp
文件、一个.txt
文件、一个.py
文件、一个.jpg
文件或任何您想要的文件,只要其中包含有效的 C++ 代码即可。
Note that including a .cpp
file is not the same as compiling it separately.请注意,包含.cpp
文件与单独编译不同。 And people expect that .cpp
files are compiled separately, not included.人们期望.cpp
文件是单独编译的,而不是包含在内。 To avoid confusing other programmers or the future version of yourself, you should rename the file to something else if you want to include it.为避免混淆其他程序员或您自己的未来版本,如果要包含它,应将文件重命名为其他名称。 You don't have to, but you should.你不必,但你应该。 If it's not a normal header file either (because you can't include it more than once), then you can make up some completely different extension, like .inc
.如果它也不是一个普通的头文件(因为你不能多次包含它),那么你可以组成一些完全不同的扩展名,比如.inc
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.