Hello,
I've got three files, main.cpp, test.h (the header file), and test.cpp, (implementation of test.h).

Both main.cpp and test.cpp #include test.h, but I don't seem to be able to get test.h to use the implementation in test.cpp (leading to "undefined reference" errors when attempting to compile).

Searching Google, I've found that g++ should automatically link test.cpp to test.h, but that does not appear to be the case here...

#Including test.cpp (in main.cpp) instead of test.h worked, but Google tells me this is not an especially good idea.

The contents of main.cpp:

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

int main() {
        Test MyClass;

        MyClass.say_hi();

        return 0;
}

The contents of test.h:

#ifndef TEST_H
#define TEST_H

class Test {
        public:
                void say_hi();
};

#endif

The contents of test.cpp:

#ifndef TEST_CPP
#define TEST_CPP

#include <iostream>
using namespace std;

void Test::say_hi() {
        cout << "Hello, world\n";
}

#endif

G++'s output:

$ g++ -Wall -o test main.cpp
/tmp/cc9Lh1zk.o: In function `main':main.cpp:(.text+0x23): undefined reference to `Test::say_hi()'
collect2: ld returned 1 exit status

Thanks for your help...

Recommended Answers

All 4 Replies

Member Avatar for iamthwee

#Including test.cpp (in main.cpp) instead of test.h worked

So what's the problem, other than google saying its a no no?

You really want to separately compile and then link each compiled output. I'm not too sure of the syntax, but something like this:

$ g++ -Wall -o test main.cpp test.cpp

Don't #include source in other modules. And I don't think you want to call your executable test.

including test.cpp really won't hurt anything since the code is so small it when you get hundreds of lines of code it makes a differance. But its good practice to compile separte.

You really want to separately compile and then link each compiled output. I'm not too sure of the syntax, but something like this:

$ g++ -Wall -o test main.cpp test.cpp

Don't #include source in other modules.

That worked, thanks!

And I don't think you want to call your executable test.

That was just a simple example; the program I was having trouble with was kind of long, so I figured I'd just make a smaller one that cut right to the problem.

Thanks for your help! :cheesy:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.