-1

I've gone through many similar threads on this kind of question but I'm still unable to resolve this error. Any help would be appreciated.

/*samp.h header file*/

#include<iostream>
using namespace std;

class test
{
private:
test();
public:
static void const_caller();
};

/*samp.cpp file*/

#include<iostream>
using namespace std;

class test
{
private:
test()
{
cout<<"priv cont called\n";
}
public:
static void const_caller()
{
cout<<"calling priv const\n";
}
};

/*main.cpp file */

#include"samp.h"
using namespace std;

int main(int argc, char **argv)
{
test::const_caller();
}

when I do

g++ samp.cpp main.cpp -o main.out

I get this error

/usr/bin/ld: /tmp/ccHZVIBK.o: in function `main':
main.cpp:(.text+0x14): undefined reference to `test::const_caller()'

which I'm unable to resolve since quite some time now.

virmis_007
  • 173
  • 1
  • 4
  • 17
  • The shown code should not even compile, much less get to the link stage. What exactly is the shown code including? Most of the `#include`s are missing what's actually getting included. Furthermore, even what's left of the shown code there are obvious fundamental issues. You do not define class methods by copy/pasting the entire class declaration, and then defining class methods inline. C++ does not work this way. Perhaps [you can try a better C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)? – Sam Varshavchik May 22 '20 at 21:03

2 Answers2

1

With your posted code, the .cpp file contains its own definition of the class that has the same name as the class in the .h file but it is really a different class.

In the .cpp file, you need to use:

test::test()
{
   cout<<"priv cont called\n";
}

void test::const_caller()
{
   cout<<"calling priv const\n";
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

In the samp.cpp file you define test class again.

You need to include samp.h header and implement methods of test class:

#include "samp.h"

using namespace std;

test::test()
{
    cout << "priv cont called\n";
}

void test::const_caller()
{
    cout << "calling priv const\n";
}
Dmytro
  • 1,290
  • 17
  • 21