简体   繁体   中英

How to share variable between projects in the same solution?

How to share variable between two projects in the same solution? I've tried to use extern, static, getters/setters and nothing seems to work. What I want to achieve is to set work variable in in project and pass it's value to another project called worker so that it can use it and do some calculations. This is the code:

Solution is named Sharing:

Sharing/MainApp:

MainApp.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, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);

   if (!hWnd)
   {
      return FALSE;
   }

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

   return TRUE;
}

Sharing/Worker:

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;
}

Compilation error:

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   

Differenf projects (and running processes) have different memory. You should use "external" methods. For example, shared memory: https://www.boost.org/doc/libs/1_54_0/doc/html/interprocess/sharedmemorybetweenprocesses.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM