Search code examples
c++idecodeblocksbuild-error

Is this a bug in "Code::Blocks" or I am doing something wrong


I made this simple c++ program in code::blocks IDE:

#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;
}

and this function:

#include <iostream>

using namespace std;

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

when I create the function in the IDE by creating new empty file and try to build the program it returns this error:

enter image description here

but when I create the same function file manually by the text editor and put it in the same folder of the project it works fine and the compiler can build it with no errors.

So is this because I am doing something wrong or is it a bug in the IDE ?

Can you help me out of this ?

and thanks in advance.


Solution

  • You are messing up the project:

    1st you should do is create a header file function.h or function.hpp, in there place the header of the function

    function.h:

    float funct(float x, float y);
    

    then a

    function.cpp: that is where the concrete implementation happens:

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

    then you are ready to include that into another file:

    #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;
    }
    

    you can for sure see a dirty/not_good-practice version where there is no header

    in that version no include is required, but you need to prototype the functions you need

    function.cpp: that is where the concrete implementation happens:

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

    and the main:

    #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;
    }
    

    as Neil Butterworth said above, no cpp files must be included..