Today, when doing the AVT camera driver, after compiling this problem, I defined a static member variable in a class, but the compiler always error: "Error LNK2005 static Vimbasystem ... already defined in the. obj.
The code is roughly as follows:
CameraBase.h
1 #pragmaOnce2 classCamerabase3 {4 Public:5 Static voidinstance ();6 Virtual voidOpen () =0;7 8 protected:9 StaticVimbasystem &system;Ten }
One Vimbasystem &camerabase::system = Vimbasystem::getinstance (); Static member variables must be initialized outside of the class, or an error will be A - classCAMERAAVT: PublicCamerabase - { the Public: - voidopen ();
-}
CameraBase.cpp
1 " cameraBase.h " 2 void camerabase::instance () 3 {4 System. Startup (); 5 }
CameraAvt.cpp
1 " cameraBase.h " 2 void Cameraavt::open () 3 {4 system. Opencamerabyid (Null,vmbaccessmodefull,camera); 5 }
When I initialize a static member variable in the cameraBase.h header file, the error is:
Error:error LNK2005 static Vimbasystem ... Already defined in ... obj
After the online search for information, found the answer, referring to the online statement:
When you first generate obj using the CPP file for this header, the system defines it, and when another CPP that uses the header again generates obj [separately], the system is defined, and then two obj is joined by another CPP that also contains the head. Duplicate definitions will appear.
As long as two CPP files contain an H file that defines the variable, an error will be made.
So as long as the system initialization in the CameraBase.cpp file is completed, it can be compiled successfully, that is, CameraBase.cpp:
1 " cameraBase.h " 2 Vimbasystem &camerabase::system = vimbasystem::getinstance (); 3 void camerabase::instance () 4 {5 system. Startup (); 6 }
Just remember, do not initialize the static member variable in the H file, put in the CPP to complete, there is no mistake.
Static member variable initialization in VS Error "error LNK2005 static Vimbasystem ... already defined in the. obj