问题描述
如何在同一个解决方案中的两个项目之间共享变量?我尝试使用 extern、static、getter/setter,但似乎没有任何效果。我想要实现的是在项目中设置工作变量并将其值传递给另一个名为 worker 的项目,以便它可以使用它并进行一些计算。这是代码:
解决方案名为共享:
分享/主应用:
主应用程序.h
#pragma once
#include "resource.h"
MainApp.cpp:
#include "framework.h"
#include "Sharing.h"
#include "../Worker/Worker.h"
...
BOOL InitInstance(HINSTANCE hInstance,int nCmdshow)
{
work = 33; //<- here I want to assign value and pass it to Worker project
hInst = hInstance;
HWND hWnd = CreateWindowW(szWindowClass,szTitle,WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,nullptr,hInstance,nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd,nCmdshow);
UpdateWindow(hWnd);
return TRUE;
}
分享/工作者:
Worker.h:
#ifdef WORKER_EXPORTS
#define WORKER_API __declspec(dllexport)
#else
#define WORKER_API __declspec(dllimport)
#endif
// This class is exported from the dll
class WORKER_API CWorker {
public:
CWorker(void);
// Todo: add your methods here.
};
extern WORKER_API int nWorker;
extern int work; // <- this does not work
WORKER_API int fnWorker(void);
Worker.cpp:
// Worker.cpp : Defines the exported functions for the DLL.
//
#include "pch.h"
#include "framework.h"
#include "Worker.h"
// This is an example of an exported variable
WORKER_API int nWorker=0;
int work; // <- here
// This is an example of an exported function.
WORKER_API int fnWorker(void)
{
return 0;
}
// This is the constructor of a class that has been exported.
CWorker::CWorker()
{
return;
}
编译错误:
Error LNK2001 unresolved external symbol "int work" (?work@@3HA) Sharing C:\..\..\..\..\..\Sharing\Sharing.obj 1
Error LNK1120 1 unresolved externals Sharing C:\..\...\..\..\..\Debug\Sharing.exe 1
解决方法
不同的项目(和正在运行的进程)有不同的内存。您应该使用“外部”方法。例如,共享内存:https://www.boost.org/doc/libs/1_54_0/doc/html/interprocess/sharedmemorybetweenprocesses.html