首页 > 解决方案 > 如何在同一解决方案中的项目之间共享变量?

问题描述

如何在同一解决方案中的两个项目之间共享变量?我尝试使用外部、静态、getter/setter,但似乎没有任何效果。我想要实现的是在项目中设置工作变量并将其值传递给另一个名为 worker 的项目,以便它可以使用它并进行一些计算。这是代码:

解决方案名为共享:

共享/主应用程序:

主应用程序.h

#pragma once

#include "resource.h"

主应用程序.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, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}

共享/工作者:

工人.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);

工人.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   

标签: c++variablesprojectshare

解决方案


不同的项目(和正在运行的进程)具有不同的内存。您应该使用“外部”方法。例如共享内存:https ://www.boost.org/doc/libs/1_54_0/doc/html/interprocess/sharedmemorybetweenprocesses.html


推荐阅读