Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing extern and const

Can I mix extern and const, as extern const? If yes, does the const qualifier impose it's reign only within the scope it's declared in or should it exactly match the declaration of the translational unit it's declared in? I.e. can I declare say extern const int i; even when the actual i is not a const and vice versa?

like image 363
legends2k Avatar asked Feb 03 '10 09:02

legends2k


People also ask

Can we use extern with const in C?

Yes, you can use them together. If you declare "extern const int i", then i is const over its full scope. It is impossible to redefine it as non-const.

What does extern const mean?

In a const variable declaration, it specifies that the variable has external linkage. The extern must be applied to all declarations in all files. (Global const variables have internal linkage by default.) extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention.

How do I use extern in CPP?

The “extern” keyword is used to declare and define the external variables. The keyword [ extern “C” ] is used to declare functions in C++ which is implemented and compiled in C language. It uses C libraries in C++ language.

What is extern void?

extern "C" void foo(); This means the function foo will be linked using the C conventions for linkage (maybe because this is a function defined in a C library or is a function intended to be called by C programs).


1 Answers

  • Yes, you can use them together.
  • And yes, it should exactly match the declaration in the translation unit it's actually declared in. Unless of course you are participating in the Underhanded C Programming Contest :-)

The usual pattern is:

  • file.h:
    extern const int a_global_var;
  • file.c:
    #include "file.h"
    const int a_global_var = /* some const expression */;

Edit: Incorporated legends2k's comment. Thanks.

like image 183
edgar.holleis Avatar answered Sep 28 '22 16:09

edgar.holleis