0

Created project in visual studio 2008.Now we want to split the project into many library files(DLL) but the problem is we have global variables which are in separate globals.h file using this file we are accessing global variables across project using extern keyword which are declare in externals.h.

How to share these global variables information across different library files ???

globals.h   externs.h
int a=0;     extern int a;
int b=0;     extern int b;
...        ...
...        ...

NOTE:globals.h is included only once in project.

1 Answers1

0

The usual approach for global variables is the following:

globals.h
extern int a;
extern int b;

globals.c
int a = 1;
int b = 2;

Note that the actual definition of the variables are in a c (or cpp) file.

If your are exporting global variables from a dll additional steps has to be performed.

globals.h
#ifdef MYDLL_EXPORTS
#define MYDLL_API __declspec(dllexport)
#else
#define MYDLL_API __declspec(dllimport)
#endif

extern MYDLL_API int a;
extern MYDLL_API int b;

globals.c
#include "globals.h"

MYDLL_API int a = 1;
MYDLL_API int b = 2;

You have to define MYDLL_EXPORTS when you build your dll. If you use it from other dll's or executables, it must be not defined.

The __declspec(dllexport) tells the linker: This symbol (variable, function, class) will be used by other dlls or applications.

The __declspec(dllimport) tells the compiler: This symbol isn't defined in this project, but in an other dll.

Markus Mayer
  • 534
  • 7
  • 8
  • got error regarding static variable declared in class while converting to dll's....can you provide documentation or notes, link regarding library creation using visual studio 2008 on windows. –  Sep 05 '14 at 06:41
  • Maybe http://msdn.microsoft.com/en-us/library/81h27t8c.aspx or http://stackoverflow.com/questions/3491990/c-definition-of-dllimport-static-data-member can help you. – Markus Mayer Sep 05 '14 at 07:31