0

I am new to C++ and I am trying to use C++ source files in combination with the header files. I surfed through the internet and found this article from Microsoft on C++ header files. I did exactly the same thing but my code doesn't work. Can anyone please guide me what am I doing wrong.

This is the folder tree.

library
├── Class.cc
├── Class.hh
└── Main.cc

Here is my code:

// Class.cc
#include "Class.hh"

using namespace mynamespace;

int Class::get_field(void)
{
    return -1;
}
// Class.hh
namespace mynamespace
{
    class Class
    {
    public:
        int get_field(void);

    };
}

// Main.hh
#include <iostream>
#include "Class.hh"

using namespace std;
using namespace mynamespace;


int main(int argc, char const *argv[])
{
    Class c = Class();
    cout << c.get_field() << endl;
    return 0;
}

This is the output:

/tmp/ccyKPmWv.o: In function `main':
Main.cc:(.text+0x26): undefined reference to `mynamespace::Class::get_field()'
collect2: error: ld returned 1 exit status

In the Main.cc file when I replace #include "Class.hh" with #include "Class.cc" then it works as expected!

  • 1
    TL;DR you have to compile both `Main.cc` and `Class.cc` in one command. How do you compile your code? And you should never `#include` `.cc` files. – Yksisarvinen Mar 26 '20 at 10:28
  • This means get_field is declared but not implemented. The linker does not see the implementation. – armagedescu Mar 26 '20 at 10:34
  • @armagedescu To be precise, we see the implementation of `get_field`. It's just not provided to the linker (and probably not to compiler either). – Yksisarvinen Mar 26 '20 at 10:42

1 Answers1

0

How are you compiling? By hand? Then you have to feed both .cc files in the compiler, or if you first compile and then link compile both and link both resulting object files.

If you use an IDE you should add both files (and in my opinion also the header) to your project file.

Hazardy
  • 116
  • 1
  • 4
  • This looks like a linker error, not a compiler error. – Jasper Kent Mar 26 '20 at 10:35
  • It is a linker error, but if the ``Class.cc`` is not compiled, the linker is not at fault. ;) Same if it is compiled, but the linker does not get the object file. – Hazardy Mar 26 '20 at 11:46