-5

I'm trying to work with classes in separate files in CodeBlocks but I'm getting the following problem.

I have 3 files: main.cpp, clasa.h and clasa.cpp.

clasa.h

#pragma once

class clasa
{
public:
    clasa();
};

clasa.cpp

#include "clasa.h"
#include <iostream>
using namespace std;

clasa::clasa()
{
    cout<<"hi";
}

main.cpp

#include <iostream>
#include "clasa.h"

using namespace std;

int main()
{
    clasa obj;
    return 0;
}

When I include these 3 files into a project, the output is hi.

When I DON'T include them into a project, main.cpp just doesn't build. But if i replace "clasa.h" with "clasa.cpp" it works again.

Why does it not work otherwise?

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
  • 5
    It compiles when you include all the code. It doesn’t compile when you leave some of it out. What’s the question, exactly?! – Biffen Apr 02 '18 at 14:08
  • 1
    Perhaps the question [Why should I not include cpp files and instead use a header?](https://stackoverflow.com/questions/1686204/why-should-i-not-include-cpp-files-and-instead-use-a-header) would be useful for you. – François Andrieux Apr 02 '18 at 14:12
  • 2
    This question seems to lie somewhere between _what does a linker do_ and _what does #include do_. As asked, "Why does {omitting source code} not work?" is not a well-formed question, in my opinion. – Drew Dormann Apr 02 '18 at 14:27
  • 2
    Voted to close as "too broad". Without explaining what is understood and what is not understood, this question is asking for a rather large tutorial on the basics of writing, compiling, and linking C++. – Drew Dormann Apr 02 '18 at 14:50

1 Answers1

0

TL;DR - It looks like you are not compiling the header file (*.h) in the the built executable.

When you click the run button the computer does two things. First it compiles the code and makes an executable. Then it runs the executable. First how does the compiler work? It reads *.cpp and when it comes across "#include" it replaces that line the code from the specified file. After the compiler processes the #include "clasa.h" line the main.cpp file will look like this:

#include <iostream>
#pragma once
class clasa
{
public:
    clasa();
};

using namespace std;

int main()
{
    clasa obj;
    return 0;
}

It does the same for the also. When you remove the *.h file from the project the compiler does not include the code in the executable. The reason it works with the *.cpp variant is because the compiler does not include *.cpp files. They are accessed as the program in run. Hope this helped you.

Mdogdope
  • 11
  • 4