有如下程序逻辑结构,主程序中调用两个动态库,动态库中,含有相同名字的全局变量,在后加载库的函数中,更改全局变量值,使用GDB查看时,值未更改。
主程序代码如下:
#include <stdio.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <dlfcn.h>
#include <unistd.h>
#endif//_WIN32
typedef void (*DLL_FUNC)(void);
int main(void)
{
#ifdef _WIN32
HMODULE handle[2];
DLL_FUNC func[2];
handle[0] = LoadLibraryA("dll1.dll");
func[0] = (DLL_FUNC)GetProcAddress(handle[0], "func");
handle[1] = LoadLibraryA("dll2.dll");
func[1] = (DLL_FUNC)GetProcAddress(handle[1], "func");
func[0]();
func[1]();
FreeLibrary(handle[0]);
FreeLibrary(handle[1]);
#else
void *handle[2];
DLL_FUNC func[2];
handle[0] = dlopen("libdll1.so", RTLD_LAZY);
func[0] = (DLL_FUNC)dlsym(handle[0], "func");
handle[1] = dlopen("libdll2.so", RTLD_LAZY);
func[1] = (DLL_FUNC)dlsym(handle[1], "func");
func[0]();
func[1]();
dlclose(handle[0]);
dlclose(handle[1]);
#endif//_WIN32
getchar();
return 0;
}
动态库libdll1.so的代码如下:
Dll1.cpp:
#include <stdio.h>
#ifdef _WIN32
#define EXPORT_API __declspec(dllexport)
#else
#define EXPORT_API
#endif//
#ifdef __cplusplus
extern "C" {
#endif
int dllInt = 0;
extern void refer1(void);
extern void diff(void);
EXPORT_API void func(void)
{
printf("Dll1\n");
refer1();
diff();
}
#ifdef __cplusplus
};
#endif
refer.cpp:
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
extern int dllInt;
void refer1(void)
{
dllInt = 1;
printf("Dll1::refer1 dllInt=%d\n", dllInt);
}
void diff(void)
{
printf("Dll1::diff dllInt=%d\n", dllInt);
}
#ifdef __cplusplus
};
#endif
动态库libdll2.so代码与libdll1.so类似,详细可下载全部代码https://download.youkuaiyun.com/download/xiejianjun417/12240611
运行上面的程序,使用gdb调试,如下图:
可以看到在调用libdll2.so中的函数refer2更改dllInt时,显示值未更改。但是通过printf显示是正确的。未找到解决方法,据说有命令可能查看到不同范围的全局变量,但是一直未找到。