我现在正在学习 C++,有 Python 背景,但在理解 C++ 如何处理多个源文件方面遇到了一些困难。在 Python 中,导入语句首先检查您尝试导入的模块的当前工作目录,然后检查 sys.path 中的目录。在 C++ 中,我应该在哪里放置自定义的 .h 文件?编译器会在哪里查找?
例如,我有一个程序 foo.exe,它是从单个源文件 foo.cpp 编译而来的,两者都位于同一目录中。我决定要更好地组织事情,所以我创建了一个新的 .h 文件 bar.h 并将内容转储到其中。我是否只需要 #include 即可获取我放在那里的东西?如果我想将 bar.h 与另一个程序(在完全不同的目录中)一起使用怎么办?
最佳答案
有两个 include
变体:
#include "path-spec"
#include <path-spec>
引用符号:
This form instructs the preprocessor to look for include files in the same directory of the file that contains the #include statement, and then in the directories of any files that include (#include) that file.
括号符号在某些定义的位置查找头文件。
使用gcc
,您可以通过以下方式获取有关这些路径的一些信息:
$ echo | gcc -v -x c++ -E -
编译器接受
-I 或/I
添加额外路径的选项。
关于c++ - C++ 如何处理多个源文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1787174/