Functional description
Lib1 is the DLL dynamic library 1. Lib1 contains A global class instance A. Exe and other DLL dynamic library modules can share this instance A globally.
Key code implementation
IDE: VisualStudio 2015
Framework: MFC (others similar)
The COne class in Lib1:
H #pragma once class AFX_EXT_CLASS COne {public: ~COne(); COne(); public: int a; }; __declspec(dllimport) extern COne one; // Global class instance, declaredCopy the code
CPP #include "stdafx.h" #include "one.h" #include <iostream> using namespace STD; COne one; // The global class variable defines COne::COne() {a = 100; Cout << "COne initialization "<< endl; } COne::~COne() { }Copy the code
Public H.h: Used to import one.h files
#pragma once #include ".. /MFCLibrary1/One.h"Copy the code
Lib2 defines the CTwo class, which uses an instance of class one
//CTwo.h
#pragma once
class AFX_EXT_CLASS CTwo
{
public:
CTwo();
~CTwo();
int get();
};
Copy the code
//CTwo.cpp #include "stdafx.h" #include "Two.h" #include ".. /include/h.h" #include ".. /MFCLibrary1/One.h" CTwo::CTwo() { } CTwo::~CTwo() { } int CTwo::get() { one.a += 1000; return one.a; }Copy the code
EXE is called
// TODO: Code the behavior of the application here. int ret1 = one.a; CTwo two; int ret2 = two.get(); int ret3 = two.get(); int ret4 = one.a; system("pause");Copy the code
Execution result: COne is only instantiated once! :smile::smiley:
COne initializationCopy the code
The sample code: wwa.lanzous.com/iAlACokigcf