【问题标题】:Is this a bug in "Code::Blocks" or I am doing something wrong这是“代码::块”中的错误还是我做错了什么
【发布时间】:2017-09-28 07:24:25
【问题描述】:

我在 code::blocks IDE 中制作了这个简单的 c++ 程序:

#include <iostream>
#include "funct.cpp"
using namespace std;

int main()
{
    float a, b;
    cout << "enter a : ";
    cin >> a;
    cout << "enter b : ";
    cin >> b;
    cout << "\n\nThe result is: " << funct(a, b) << "\n";
    return 0;
}

还有这个功能:

#include <iostream>

using namespace std;

float funct(float x, float y)
{
    float z;
    z=x/y;
    return z;
}

当我通过创建新的空文件在 IDE 中创建函数并尝试构建程序时,它返回此错误:

但是当我通过文本编辑器手动创建相同的函数文件并将其放在项目的同一文件夹中时,它可以正常工作并且编译器可以毫无错误地构建它。

这是因为我做错了什么还是 IDE 中的错误?

你能帮我解决这个问题吗?

提前致谢。

【问题讨论】:

标签: c++ ide codeblocks build-error


【解决方案1】:

你把项目搞砸了:

你应该做的第一件事是创建一个头文件function.hfunction.hpp,在那里放置函数的头

function.h

float funct(float x, float y);

然后一个

function.cpp:这是具体实现发生的地方:

float funct(float x, float y)
{
    float z;
    z = x / y;
    return z;
}

那么您就可以将其包含到另一个文件中了:

#include <iostream>
#include "funt.h"
using namespace std;

int main()
{
    float a, b;
    cout << "enter a : ";
    cin >> a;
    cout << "enter b : ";
    cin >> b;
    cout << "\n\nThe result is: " << funct(a, b) << "\n";
    return 0;
}

您肯定会看到没有标题的脏/非良好实践版本

在该版本中不需要包含,但您需要对所需的功能进行原型设计

function.cpp:这是具体实现发生的地方:

float funct(float x, float y)
{
    float z;
    z = x / y;
    return z;
}

还有主要的:

#include <iostream>
using namespace std;
float funct(float x, float y);

int main()
{
    float a, b;
    cout << "enter a : ";
    cin >> a;
    cout << "enter b : ";
    cin >> b;
    cout << "\n\nThe result is: " << funct(a, b) << "\n";
    return 0;
}

正如上面 Neil Butterworth 所说,不能包含任何 cpp 文件。

【讨论】:

    【解决方案2】:

    不要包含 .cpp 文件。而是将函数的前向声明放在看起来像 float funct(float x, float y); 的 .h 或 .hpp 文件中,并包含该文件。

    【讨论】:

    • "而是在 .h 或 .hpp 中放置函数的前向声明" wut? o_O
    • 添加另一个名为“funct.h”或“funct.hpp”的文件(不管哪个),在里面放float funct(float x, float y);,这叫做前向声明。去掉 #include "funct.cpp" 并用 #include "funct.h"#include "funct.hpp" 替换它(无论你做了哪个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    相关资源
    最近更新 更多