-2

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.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97

2 Answers2

1

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..

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Don't include .cpp files. Instead put a forward declaration of the function in a .h or .hpp file that would look like this float funct(float x, float y);, and include that file.

Qyriad
  • 54
  • 5
  • "Instead put a forward declaration of the function in a .h or .hpp" wut? o_O – George Apr 30 '17 at 18:13
  • Add another file called "funct.h" or "funct.hpp" (it doesn't matter which), and in it just put `float funct(float x, float y);`, this is called a forward declaration. Get rid of the `#include "funct.cpp"` and replace it with `#include "funct.h"` or `#include "funct.hpp"` (for whichever one you did. – Qyriad Apr 30 '17 at 18:15