0

When I compile a C++ project in eclipse it shows me errors saying that all functions in IO.cpp are already defined.

This is my code:

File: IO.cpp

#include <string>
#include <iostream>

using namespace std;

void print(string line) {
    cout << line;
}

void println(string line) {
    cout << line << endl;
}

void printError(string message, string error, string file) {
    cout << "An error occurred!" << endl;
    cout << "Message: "+ message << endl;
    cout << "Error: "+ error << endl;
    if(file != "") {
        cout << "File/Method: "+ file << endl;
    }
}

File: main.cpp

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

using namespace std;

int main()
{
    println("Hello world!");
}
aiko
  • 423
  • 1
  • 4
  • 11

2 Answers2

0

You should remove the line below from main.cpp

#include "IO.cpp"

And add following lines afer using namespace std

void print(string line);
void println(string line);
void printError(string message, string error, string file);

If you include a cpp file again which is also present in your project source list (files to be compiled), your program will get multiple definitions for the same functions which is not allowed in C++. On the other hand, the alternative suggested here consists of declarations of function, which is allowed to present several times, but must present atleast once before first use.

Standard practice is to move the declarations in a header file (for ex: IO.h) and include this header file in both IO.cpp and main.cpp

Further readings:
Difference between declarations and definitions

Community
  • 1
  • 1
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • Thanks I thought that the compiler wouldn't compile IO.cpp if it isn't included in main.cpp (like PHP) – aiko Aug 30 '14 at 17:44
0

You included module IO.cpp in module main.cpp

#include "IO.cpp"

So you have gotten the function definitions in two modules: IO.cpp and in main cpp

You should create a header file for example IO.h and place there all function declarations. Then you have to include this header file in IO.cpp and main.cpp

For example

IO.h

#include <string>


void print( std::string line);

void println( std::string line);

void printError( std::string message, std::string error, std::string file);

IO.cpp

#include <string>
#include <iostream>
#include <IO.h>

using namespace std;

void print(string line) {
    cout << line;
}

void println(string line) {
    cout << line << endl;
}

void printError(string message, string error, string file) {
    cout << "An error occurred!" << endl;
    cout << "Message: "+ message << endl;
    cout << "Error: "+ error << endl;
    if(file != "") {
        cout << "File/Method: "+ file << endl;
    }
}

main.cpp

#include <IO.h>

//...
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thanks I thought that the compiler wouldn't compile IO.cpp if it isn't included in main.cpp (like PHP) – aiko Aug 30 '14 at 17:45