Monday 28 November 2016

c++ - Including .cpp files



I have read in places like here that you have to include .h files and not .cpp files, because otherwise then you get an error. So for example




main.cpp



#include 
#include "foop.h"

int main(int argc, char *argv[])
{
int x=42;
std::cout << x <std::cout << foo(x) << std::endl;

return 0;
}


foop.h



#ifndef FOOP_H
#define FOOP_H
int foo(int a);
#endif



foop.cpp



int foo(int a){
return ++a;
}


works, but if I replace #include "foop.h" with #include "foop.cpp" I get an error (Using Dev C++ 4.9.9.2, Windows):




multiple definition of foo(int)
first defined here


Why is this?


Answer



What include does is copying all the contents from the file (which is the argument inside the <> or the "" ), so when the preproccesor finishes its work main.cpp will look like:



// iostream stuff


int foo(int a){
return ++a;
}

int main(int argc, char *argv[])
{
int x=42;
std::cout << x < std::cout << foo(x) << std::endl;

return 0;
}


So foo will be defined in main.cpp, but a definition also exists in foop.cpp, so the compiler "gets confused" because of the function duplication.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...