简体   繁体   中英

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.

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-specification 19 (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;
}

extern extern "C" int A; ?

extern "C" can be used as a block:

extern "C"
{
    extern int A;
}

The declaration needs to be in a header file like Ah 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM