c++ - Creating a shared library with a global variable -
this question asked in g++ compiler context under windows.
let's want create shared library, mylibrary.dll.
mylibrary.h:
#ifndef _mylibrary_h #define _mylibrary_h #ifdef mylibrary_dll_export #define mylibrary_api __declspec(dllexport) #else #define mylibrary_api __declspec(dllimport) #endif class mylibrary_api xyz{ public: double x; }; mylibrary_api extern xyz xyz; // correct, want declare, hence "extern" #endif
mylibrary.cpp:
#include "mylibrary.h" xyz xyz; // definition of xyz
i compile 2 files,
mylibrary.dll libmylibrary.a
now, lets want use variable xyz in program link against import library (i.e. -lmylibrary), , include header mylibrary.h of course.
i seem getting undefined reference when compile.
undefined reference `__imp__zn2vx6................
how define "global" variable in shared library, i.e. variable exists in 1 copy , can shared among threads?
edit:
i turned out reason had declared variable xyz inside 2 namespace in mylibrary.h. when moved variable outside namespaces , b (i.e. global namespace) worked.
i had this:
mylibrary.h:
#ifndef _mylibrary_h #define _mylibrary_h #ifdef mylibrary_dll_export #define mylibrary_api __declspec(dllexport) #else #define mylibrary_api __declspec(dllimport) #endif namespace a{ namespace b{ class mylibrary_api xyz{ public: double x; }; mylibrary_api extern xyz xyz; // correct, want declare, hence "extern" } // b } // #endif
mylibrary.cpp:
#include "mylibrary.h" a::b::xyz xyz; // definition of xyz
i tried use xyz outside mylibrary referring as
a::b::xyz
question: refer xyz in wrong way or must place global variables in shared libraries in global namespace?
Comments
Post a Comment