0

I am try to place a class in a separate file using c++ but without including the .cpp file it is not working.

This is CPP File of the Class Example

//Example.cpp
#include "Example.h"
#include<iostream>
using namespace std;

Example::Example()
{
    cout<<"I am am Executed\n";
} 

This is header file

//Example.h
#ifndef EXAMPLE_H
#define EXAMPLE_H


class Example
{
    public:
        Example();
};
#endif

Now If I don't include the C++ file into my main function file it gives out an error

#include "Example.h"
//#include "Example.cpp"
#include<iostream>
using namespace std;
int main()
{
    Example aak;
    return 0;
}

So here I have commented out the //#include "Example.cpp", it would give me an error stating that

/tmp/ccuHMRJB.o: In function `main':
main.cpp:(.text+0x10): undefined reference to `Example::Example()'
collect2: ld returned 1 exit status

However If I uncomment the #include "Example.cpp" it works just fine! Giving me an output

I am Executed!

I don't understand why I need to include both of the files (.h as well as .cpp) to execute the program. As long as I think it should work by just including the .h file but it doesn't....

Aakash
  • 29
  • 4
  • 1
    You need to compile both source files and link them together. Please show us the commands you used to build your program. – Daniel Frey Mar 08 '13 at 18:22

2 Answers2

1

You should not include .cpp files in other .cpp files. Instead, list all the .cpp files which comprise your project on the compiler command line.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
0

this is because when you are including the cpp file the file (i.e. the function) is also being compiled. But when you are including the prototype file i.e the header file you have to also specify where to search for the executable code of function code. means where the linker would find out the library where you have stored the cpp file in binary form(already compiled) otherwise it needed to be compiled. I think the later one is your situation (i.e you haven't created a library from your cpp file). Now think If you dont include the cpp file it wont be compiled. Then you are calling a function whose binary code does not exists.


therefore the linker is throwing an error if you dont include the cpp file

deeiip
  • 3,319
  • 2
  • 22
  • 33