【问题标题】:Order of header file inclusions and dependencies头文件包含顺序和依赖关系
【发布时间】:2015-10-18 17:22:41
【问题描述】:

我只是想测试将代码拆分成多个文件。

我有:

//testMultiple.cpp

#include <string>
#include <iostream>
#include "testInclude.cpp"

int main(){
    std::cout << "hi";
}

//testInclude.cpp

class testClass{
    public:
        string x;
};

这是给testInclude.cpp:3:9: error: ‘string’ does not name a type

我想既然它在包含 testInclude.cpp 之前就包含了,那么将定义字符串以在 testInclude.cpp 中使用。

【问题讨论】:

  • 为什么要包含.cpp 文件,而不是将其与testMultiple.cpp 链接?这是非常不寻常的,并且会破坏大多数构建系统和 IDE。
  • 因为据我所知,如果你想把你的程序分成多个文件,你#include他们
  • 不,那是错误的。您将它们拆分为包含类声明的头文件和包含相应定义的.cpp 文件。其他翻译单元(.cpp 文件)使用#include 从标题中获取声明。
  • @DavidBandel 或许你应该先看几个问题,比如this one
  • @DavidBandel _"我不知道这是一个无用的包含,字符串实际上是在 iostream 中定义的。"_不,你不能依赖这个。如果您使用std::string,请使用#include &lt;string&gt;

标签: c++ dependencies header-files


【解决方案1】:

您需要使用std::string 而不是string

【讨论】:

  • 这对我没有帮助。它仍然不会使用&lt;string&gt;,这是我正在尝试做的。
  • 这里还不够。他在编译的 cpp 中声明他的类。但它失败了,因为在这个 cpp 的上下文中字符串是未知的。
  • 我改成hpp还是不行
  • 我修改了问题中的代码。矢量是一个更好的例子
  • 好的,谢谢。它按你的方式工作。我只是对向量的定义位置有一个误解。
【解决方案2】:

您包含的是 cpp 文件,而不是 hpp 文件。 常见的做法是包含头文件 (h/hpp),而不是实现 (c/cpp) 文件。

如果你只编译testMultiple.cpp,这应该可以。如果编译器单独编译testInclude.cpp,它不会看到`#include

尝试将 testInclude.cpp 重命名为 testInclude.hpp 并确保它没有被编译。

这是一个例子:

///// testInclude.h
#include <vector>
class testClass{
    public:
         std::vector<int> x; // vector is in std namespace
};

///// testMultiple.cpp
// #include <vector> - gets this through testInclude.h
#include "testInclude.h"

int main(){
}

【讨论】:

    【解决方案3】:

    使用

    class testClass{
        public:
            std::string x;
    };
    

    【讨论】:

    • 我已经有#include &lt;string&gt; 查看我的第一个文件而且我不想使用&lt;iostream&gt; 字符串。我正在尝试使用 &lt;string&gt; 字符串。我只是想将我的代码拆分成多个文件。
    • @DavidBandel 您是什么意思“我正在尝试使用&lt;string&gt; 字符串”?我没有得到你想要的,答案是正确的。这是你尝试组织代码的方式是错误的。
    • 我正在尝试将一些代码放在另一个文件中,然后包含它,以便我的代码被拆分到多个文件中。就是这样。
    • 好的,谢谢。它按你的方式工作。我只是对向量的定义位置有一个误解。
    猜你喜欢
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 2016-07-16
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多