Where are those extern declarations located? It looks like they're in some header file so where are you #including that header file. And also you need to define those variables in one and only one source file without the extern qualifier.
header.h
1 2 3 4
#pragma once
externint global_a;
void someFunction();
extern simply tells the linker the variable exists in this or another compilation unit. You don't actually define a or test_one anywhere.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include "stdafx.h"
#include "extern.h" // include extern declarations
int a = 0; // You must actually define a somewhere
class_one * test_one = new class_one; // Same goes for class_one pointer
int main()
{ std::cout << "test:" << a << std::endl;
a++;
std::cout << "test:" << a;
system("pause");
return 0;
}
The thing is, if I comment out the class declarations in the ex_declaration.h and .cpp
the programm compiles with no errors and with the extern declaration of the int a = 7;,
but if I want decalir an object of my class as extern the compiler throws these errors.
1) You have circular includes. stdafh.h includes ex_declaration.h which also includes stdafx.h. Yes, ex_declaraion.h is protected by #pragma once , but stdafx.h does not appear to be. In any case, having circular includes is a bad practice.
2) In stdafx.h, the include for ex_declaration.h precedes the include for class_one.h. Since ex_declaration.h references class_one, the include for class_one.h should precede the include for ex_declaration.h.
2) In stdafx.h, the include for ex_declaration.h precedes the include for class_one.h. Since ex_declaration.h references class_one, the include for class_one.h should precede the include for ex_declaration.h.
That's the solution, thx very much.
I ever thought that it doesn't matter in which sequence the header files are included.
Can I ask why do you want a global instance of your class? :+)
There is a Design Pattern called Singleton, even then there are lots of folks against the use of them as well.
And why you need a pointer to it? There shouldn't be a need for a naked pointer in modern C++ especially one created with new. Consider using a smart pointer, if at all. There is a lot that can be achieved with the STL.
Maybe if we knew what your actual problem involves, we could help with the design of it ? :+)