Tinggo
Tinggo

Reputation: 1137

How to extern declare an extern "C" variable

I wants to export a global variable from dll I define the global variable like below. Assume this variable is defined in A.cpp

extern "C" __declspec(dllexport) int A;

Meanwhile, within the dll, another source file B.cpp wants to use and modify this value. I am wonderring how to declare the variable within B.cpp before using it.

extern "C" int A; ? 

If in this case, how does compile recognize between declare and definition?

extern extern "C" int A; ?

It's definitely ill-formed.

Upvotes: 2

Views: 859

Answers (3)

Zan Lynx
Zan Lynx

Reputation: 54345

The declaration needs to be in a header file like A.h or other code files cannot use it. The dllexport is especially useless without a header file. You probably want some kind of DLLEXPORT macro so you can define it to dllexport and dllimport as necessary. See pretty much any Windows DLL code.

Then in a cpp file you include the header. That allows your code to use the variable which is declared extern.

In one of your cpp files you include the header AND then define the variable using the same type and name and no extern. The linker will then put the data storage for it into the same module as the rest of that cpp file and all other uses of the name get linked to that definition.

However, just like private member variables in C++ it is a bad idea to expose global variables in a DLL. It is much better to hide access to them behind function calls.

Upvotes: 0

Brian Bi
Brian Bi

Reputation: 119437

Per [basic.def]/2.2, a declaration of an object at namespace scope is a definition unless:

it contains the extern specifier (9.2.1) or a linkage-specification19 (9.11) and neither an initializer nor a function-body,
...
19 Appearing inside the brace-enclosed declaration-seq in a linkage-specification does not affect whether a declaration is a definition.

Thus:

extern "C" int A; is a declaration.

extern "C" int A = 0; is a definition.

The below defines A and B, and declares C: the effect is the same as it would be without the extern "C" block, except that the entities declared have C linkage instead of C++ linkage.

extern "C" {
    int A;
    extern int B = 0;
    extern int C;
}

Upvotes: 2

Blindy
Blindy

Reputation: 67439

extern extern "C" int A; ?

extern "C" can be used as a block:

extern "C"
{
    extern int A;
}

Upvotes: 1

Related Questions