0

C++ TDM-GCC 4.8.1 64-bit
Error: main.cpp:(.text+0x15): undefined reference to `tree::tree()'


main.cpp

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

int main(){
    tree tree1;
    return 0;
}

tree.h

#ifndef TREE_H
#define TREE_H
using namespace std;

class tree{
    public:
        tree();

};

#endif

tree.cpp

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

tree::tree(){
    cout << "Hello" << endl;
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • How do you compile your code? See http://stackoverflow.com/questions/21268483/main-cpp-text0x5f-undefined-reference-to?rq=1 for help. – harpun May 14 '17 at 11:18

1 Answers1

1

From a terminal, compile your code like this:

Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall -o main main.cpp tree.cpp

Execute your program, like this:

Georgioss-MacBook-Pro:~ gsamaras$ ./main 
Hello

Please read about linking in Linking files in g++.


By the way, I changed your code to first include the standard library iostream and then your header file, so now the code looks like this:

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

That way, I got rid of this warning:

In file included from main.cpp:1:
./tree.h:3:17: warning: using directive refers to implicitly-defined namespace
      'std'
using namespace std;
                ^
1 warning generated.

If you want, you can read more in Ordering of using namespace std; and includes?, but I think this is advanced for you right now.

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • I am not sure what you are asking. – gsamaras May 14 '17 at 12:32
  • @JanHank Sorry since this is not my answer, but you do not *execute* C++ or C code, you compile it and execute the resulting binary file. You use the term *execute* w.r.t code that runs inn an interpreter such as JavaScript, but I'm afraid that with partial compilation that's not quite true either. Regardless, never say *execute C++ code*. – iksemyonov May 14 '17 at 13:33