Is there any - at the standard level - protection against the incorrect use of extern ads in C? For example, let in one file there is

 extern int global; 

in another -

 double global = 3.1416; 

After all, mangling names is only in C ++, which, of course, in this situation will protect (at the linker level), unlike C, which must compile and not frown ...

It turns out that in the usual C - only the conscience of the programmer is an obstacle to incorrect use? There is no other mechanism (besides placing the extern declaration in the header file and including it in all project files)?

  • There is also a mechanism #define - #ifndef - #endif - nick_n_a
  • #ifndef __global_def #define __global_def double global = 3.1416; #endif #ifndef __global_def #define __global_def double global = 3.1416; #endif - nick_n_a
  • @nick_n_a and how will it help here? - D-side
  • @ D-side The fact that during the second call #ifndef will discard the "escaped" code, the first value will be encountered. If the problem is in different global values, you can use a similar #define construct to output both warning and error. - nick_n_a
  • @nick_n_a and now reread the examples in question. The problem is that the types of definitions and declarations are different, in different translation units. How can the preprocessor help here? - D-side

2 answers 2

In principle, in practice, this is what should be done: the declaration with extern should be placed in the header file, and the definition (with initializer) in a kind of implementation file including this header file . Then there is the hope that such obvious errors will cause a diagnostic message from the compiler.

There is no other “official” protection in the C.

    Let's start by understanding that this problem is not a problem of the compiler or a specific programming language. If module A is compiled today in Holland, and module B is compiled in Uryupinsk after three years, then ANY compiler or programming language will not be able to provide verification of external descriptions.

    Further, can this problem be considered a linker problem? Partly ... Ie if this particular format of the object module presupposes a type description for each external memory area, then the linker will be able to perform this check, if it is programmed for it. And climbs two problems:

    1. There are different OM formats even within the same OS.
    2. There are different linkers even for the same OM format.

    Are you talking about any specific OM format and linker?

    If we are talking about the ld linker from linux, for ELF modules, I recommend looking at its option --warn-common. It seems to me that she can issue warnings about all suspicious places.