It takes a long time to locate a strange compilation error found in encoding. Next we will post the most concise code to reproduce this problem :/**//*
Myclass. h
There is a namespace and a class
*/
# Ifndef _ my_class_h _
# DEFINE _ my_class_h _
Namespace MySpace
...{
Class myclass
...{
Public:
Int field;
};
}
# Endif
The following file declares a global pointer, because it only indicates the Declaration, so try not to include other files :/**//*
Global. h
Declare a global pointer
*/
# Ifndef _ global_h _
# DEFINE _ global_h _
Class myclass; // declare the existing types without introducing the defined header file
Extern myclass * g_obj;
# Endif
The following files use global variables and types :/**//*
Use. cpp
This file uses global object pointers and types
*/
# Include "myclass. H"
# Include "Global. H"
Void test1 ()
...{
G_obj = new myclass ();
G_obj-> Field = 1;
}
/**//*
G ++-o use. O-c use. cpp-g-wall
*/
Compiling use. cpp produces many compilation errors:
Only_use.cpp: In function 'void test1 ()': Only_use.cpp: 11: Error: Invalid use of undefined type 'struct myclass' Global. h: 9: Error: Forward Declaration of 'struct myclass' Only_use.cpp: 12: Error: Invalid use of undefined type 'struct myclass' Global. h: 9: Error: Forward Declaration of 'struct myclass' |
You may say that you must add using namespace MySpace. In fact, this sentence cannot be compiled. Of course, if you include myclass. h in global. H, you should be able to compile it. But I don't want to do this. For a pointer type, its type only needs to be declared, and definition does not need to be introduced. Too many header files may cause compilation problems.
I tried a lot of methods and finally found that I added a line in # include "myclass. H" in use. cpp: Using MySpace: myclass; then the code can be compiled.
To sum up, if the type exists in the namespace, if the type is declared in a header file, note the following when using it:
1. The type definition file is included in the previous (# include "myclass. H ")
2. Declare the type in namespace (using MySpace: myclass ;)
3. The declaration file containing the global pointer (# include "Global. H ")
4. Use it later.