Problems with global variables in a shared library project (C ++)

I have a problem with global variables in a C ++ shared library project. my library should work as a standard g ++ shared library (.so) as well as a dll. I did this by creating the files libiup_dll.cpp and libiup_dll.h, where I have something like

#ifdef BUILD_DLL

// code for the dll: wrapper functions around the classes in my shared library

#endif

in my dll, I need the setloglevel (int) and geterrormsg () functions. in all my classes, I would add all the error messages to the errormsg global variable. this variable should be returned by geterrormsg (). I implemented this with

std::string errormsg;
int loglevel;

in libiup_dll.h (external and #ifdefs, so it should be accessible worldwide) and then putting

extern std::string errormsg;
extern int loglevel;

in the .h files of my classes (outside the class, at the top of the files)

I now have two problems:

1) g++, ,

: libiup_test : GCC ++ Linker g++ -L "/home/hilboll/src/libiup/Release" -L/usr/local/lib -o "libiup_test". /src/stratcalc/SimpleStratosphericColumnCalculatorTest.o./src/interp/SimpleInterpolatorTest.o. /src/Test.o -lgsl -lhdf5 -lhdf5_cpp -lblas -liup/home/hilboll/src/libiup/Release/libiup.so: undefined loglevel' /home/hilboll/src/libiup/Release/libiup.so: undefined reference to errormsg ' collect2: ld 1 make: *** [libiup_test] 1

errormsg loglevel.

2) dll VS2008,

:\SRC\\libiup_dll\libiup_dll.h(229): C2086: 'std::string errormsg': Neudefinition         :\SRC\libiup\SRC\stratcalc..//SimpleInterpolator.h(16): Siehe Deklaration von 'errormsg' :\SRC\\libiup_dll\libiup_dll.h(234): C2086: 'int loglevel': Neudefinition         :\SRC\libiup\SRC\stratcalc..//SimpleInterpolator.h(17): Siehe Deklaration von 'loglevel'

, , VS , . SimpleInterpolator.h 16/17 extern...

, - , . !

+3
4

, , .cpp , .. . . , .

extern , " " cpp, .

, , , 2 ( ) cpp . cpp, , , . .

cpp ( cpp) extern . .

+2

, .

"extern" , .

, , :

// In a header file (declaration)
extern int myGlobal;

// In a source file (definition)
int myGlobal;

, , extern, , extern.

, , "int myGlobal" ( "extern" ). , , , myGlobal, . . extern .

, :

  • Linux, DLL, , , , , .
  • Windows, DLL ( ), , .
+3

, :

std::string errormsg;
int loglevel;

libiup_dll.h #ifdefs. , libiup_dll.h ( ) , , № 2.

, №1, - , , .

2 .c .cpp, . extern .

0

,

I implemented this by using

    std::string errormsg;
    int loglevel;

in libiup_dll.h (outside and #ifdefs, so it should be globally available),
and then putting

    extern std::string errormsg;
    extern int loglevel;

in my classes' .h files (outside the class, at the top of the files)

Instead, I think you should declare variables with externany number of header files, and then define variables without extern in the same C or CPP file.

0
source

Source: https://habr.com/ru/post/1715906/


All Articles