c++dllglobal

Import of global variable failed C++


I have dll with a code:

Dll.h:

#ifndef EXPORT
#define EXPORT __declspec(dllexport)
#endif
#ifndef IMPORT
#define IMPORT __declspec(dllimport)
#endif
#include <iostream>
#ifndef MY_GLOBALS_H
#define MY_GLOBALS_H
        
EXPORT extern int test;
        
EXPORT void pritnTestHpp() {
std::cout << "HPP:" << test << " Pointer=" << (unsigned)(&test) << std::endl;
}
EXPORT void pritnTestCpp();
#endif

Dll.cpp:

#include "Dll.h"
EXPORT int test = 0;

void pritnTestCpp() {
    std::cout << "CPP:" << test << " Pointer=" << (unsigned)(&test) << std::endl;
}

Main.cpp:

#include <iostream>
#include "Dll.h"

__declspec(dllimport) int test;

int main()
{
    test = 4;
    pritnTestHpp();
    pritnTestCpp();
    std::cout << "GUI:" << test << " Pointer=" << (unsigned)(&test) << std::endl;
}

Receiving output:

HPP:4 Pointer=3092644928

CPP:0 Pointer=3991531888

GUI:4 Pointer=3092644928

I wonder, why in .cpp is another pointer. Linking in Visual Studio works and I am not aware of any mistake.

I guided myself by memory and searched also in: Can I import a global variable from a DLL ? Can I do this with a DEF file? Exporting global variables from DLL

It seems identical but for me it does not works. Can you tell me plese, why?


Solution

  • This is not difficult, you just have to know what you are doing. That's why it's recommended to read the boring general tutorials.

    Anyway here is some working code, followed by some important build notes.

    dll.h

    #pragma once
    
    #ifdef DLL
    #define EXPORT __declspec(dllexport)
    #else
    #define EXPORT __declspec(dllimport)
    #endif
    
    #include <iostream>
    
    EXPORT extern int test;
    
    inline void printTestHpp() {
        std::cout << "HPP:" << test << " Pointer=" << &test << std::endl;
    }
    
    EXPORT void printTestCpp();
    

    dll.cpp

    #include "Dll.h"
    
    int test = 0;
    
    void printTestCpp() {
        std::cout << "CPP:" << test << " Pointer=" << &test << std::endl;
    }
    

    main.cpp

    #include "dll.h"
    
    int main()
    {
        test = 4;
        printTestHpp();
        printTestCpp();
        std::cout << "GUI:" << test << " Pointer=" << &test << std::endl;
    }
    

    Output

    HPP:4 Pointer=00007FFB6AB2D170
    CPP:4 Pointer=00007FFB6AB2D170
    GUI:4 Pointer=00007FFB6AB2D170
    

    Now the important build notes are that the preprocessor symbol DLL must be defined when building the DLL, and not be defined when building the main program. It's this trick that you seem to be missing in your attempts. Secondly, building the DLL will result in the creation of an import library (called something like dll.lib). You must link this import library with your main program, otherwise you will get unresolved symbols.

    Hope this helps.