I've got a simple problem I think. But I am unable to solve it so far as I am new to C++ programming. I have created a new C++ project to make the code as short and simple as possible (because the original code is much much longer) while keeping the problem I have. I have searched on Stackoverflow and Google and read about 50 related problems but nothing so far helped me fix it. Putting everything in one cc and one h file works, but is not what I prefer doing. Thanks in advance for the help.
I am using Ubuntu 14.04 / Code::Blocks 13.12 / gcc and g++ 4.8.2
The problem is that I want to access the function inside a class defined in a different file and while compiling works (due to the extern in file1.h) linking fails. If I just put "Simple S1;" instead of "extern Simple S1;" in file1.h and remove it from file1.cc I get a multiple declaration error which is expected. Apparently the "extern" trick doesn't work with classes while it works great with variables.
file1.h:
#ifndef FILE1_H
#define FILE1_H
class Simple
{
private:
unsigned int length = 10;
public:
void SetLength(unsigned int l) {length = l;}
unsigned int GetLength() {return length;}
};
extern Simple S1;
#endif
file1.cc:
#include <iostream>
#include "file1.h"
#include "file2.h"
int main()
{
Simple S1;
unsigned int l = GetL();
std::cout << "length=" << l << "\n";
l = 20;
l = GetL();
std::cout << "length=" << l << "\n";
return 0;
}
file2.h:
#ifndef FILE2_H
#define FILE2_H
unsigned int GetL();
#endif
file2.cc:
#include "file1.h"
#include "file2.h"
unsigned int GetL()
{
return S1.GetLength();
}
build commands and error:
g++ -std=c++11 -Wall -fexceptions -g -c file1.cc -o obj/Debug/file1.o
g++ -std=c++11 -Wall -fexceptions -g -c file2.cc -o obj/Debug/file2.o
g++ -o bin/Debug/Test obj/Debug/file1.o obj/Debug/file2.o
obj/Debug/file2.o: In function `GetL()':
file2.cc:6: undefined reference to `S1'
collect2: error: ld returned 1 exit status