编译时 G++ 未找到包含的 .cpp 文件

G++ Not Finding Included .cpp Files When Compiling

Inkey.cppKey.cpp在同一个目录,/root/src.

Compile.bat 在 /root.

当我 运行 Compile.bat 时,我收到消息“Key.cpp:没有那个文件或目录”。

提前感谢您的任何建议。

Inkey.cpp

#include <iostream>
#include <Key.cpp>

using namespace std;

int main(int argc, char *argv[]) {
    cout << "Hello from InKey" << endl;

    Key key1;

    return 0;
}

Key.cpp

#include <iostream>

using namespace std;

class Key {
    public:
        Key() {
            cout << "New Key instantiated." << endl;
        };
};

Compile.bat

@ECHO OFF

g++ "src/Inkey.cpp" -o "out/InKey.exe"

"out\Inkey.exe"

查找 #include "filename"#include <filename> 之间的区别。前者从当前目录开始,后者使用搜索路径(或一组这样的路径)。 (请注意,如果从当前目录开始找不到文件,#include "filename" 将退回到 #include <filename> 的搜索策略。

此外,您通常不包含 .cpp 文件,而是将它们作为单独的参数传递给编译器,然后使用链接器组合它们。

首先,将 Key.cpp 重命名为 Key.h。将声明放在 Key.h 中。然后将定义放在 Key.cpp 中(不要忘记在这里包含 Key.h )。然后使用 Key 对象将您的 Key.h 包含在所有文件中。
现在,用 g++ -o filename.out file1.cpp file2.cpp -O3 -Wall
编译它们 另外,学习使用样板代码

P.S. as @SoronelHaetir has suggested, use "" to include custom header files