These are my files. I am trying to print a line using another class from main.cpp but it gives an error "undefined reference to poddy:poddy()"
main.cpp
#include <iostream>
#include "poddy.h"
using namespace std;
int main() {
poddy le;
return 0;
}
poddy.h
#ifndef PODDY_H
#define PODDY_H
class poddy {
public:
poddy();
};
#endif // PODDY_H
poddy.cpp
#include "poddy.h"
#include <iostream>
using namespace std;
poddy::poddy() {
cout << "I am llalala and use anoder class" << endl;
}
Please help me out!
Your C++ code is correct. The "undefined reference" is a linker error that has to do with the way you are compiling your code. In order for it to link, use this command line:
g++ poddy.cpp main.cpp
Here are the details: the process of compiling C++ code has three major stages - preprocessing, compiling, and linking. Preprocessor deals with #define
and #include
statements in your code. Compiler takes the results of preprocessing, and produces binary code for each translation unit (in your case, there are two translation units - poddy.cpp
and main.cpp
). Finally, the linker establishes connections between parts of binary code within translation units.
The preprocessor and the compiler can do their job even when presented with one translation unit at a time. The linker, however, must "see" all translation units at once. When you call g++
without additional flags, all stages of the compiler are invoked, including the linker. That's why you need to list all translation units at once.