0

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...

4
Contributors
4
Replies
5
Views
11 Years
Discussion Span
Last Post by Darkmeerkat
0

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

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

0

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.

0

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.

0

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:

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.