简体   繁体   中英

extern “C” with const

We have a piece of C-code in our system which contains a few arrays like this with global access:

source.h

extern const int magic[5];

source.c:

const int magic[] = { 1, 2, 3, 4, 5};

Somebody decided it would be a good idea to change this to C++ and so the above ended up in an extern "C" block:

source.h:

extern "C" { 
    const int magic[5]; 
}

source.cc:

extern "C" {
    const int magic[] = { 1, 2, 3, 4, 5};
}

This compiled without a squeak with gcc -Wall

It wasn't until someone tried to use that array that we discovered the problem. using const inside an extern "C" causes no external symbol to be generated at all. This happens with gcc, sun workshop and ibm's compiler.

I'm somewhat at a loss as to whether or not this is expected behaviour, given that gcc doesn't warn you that you're doing something odd.

So is this behaviour for this specified by the standard, or is it a rather pervasive bug?

const variables have internal linkage (as if declared static ) unless you use extern to specify external linkage. You'll need external linkage if you want to define it in one source file and access it from others.

That's in addition to using extern "C" to specify the language linkage.

extern "C" { 
    extern const int magic[5]; 
}

Your C declaration correctly specified external linkage; but you removed it when you changed to C++.

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