2

b.c fails to compile but b.cpp can be compiled. I don't quite understand the difference of extern between C and C++. Could anybody help explain why b.c does not work but b.cpp does? Thanks.

$ cat b.c 

extern int b;
int a = b;
$ gcc -g -Wall -pedantic -c -o b.o b.c
b.c:4:9: error: initializer element is not a compile-time constant
int a = b;
        ^
1 error generated.
$ cat b.cpp 

extern int b;
int a = b;
$ g++ -g -Wall -pedantic -c -o b.o b.cpp
$ ls -g b.o 
-rw-r--r-- 1 staff 2640 Jan  5 10:22 b.o
user1424739
  • 11,937
  • 17
  • 63
  • 152
  • If I recall correctly, C does not support runtime initialization like that of a global variable. – Eljay Jan 05 '19 at 16:32

3 Answers3

6

There is no significant difference between extern variables in C and C++. What is different, is the rule for valid initializers. In C, the initializer of a variable with static storage duration must be a compile time constant. In C++, it can be pretty much any expression (including a complicated function call).

5

It's not an extern issue.

Error "initializer element is not constant" when trying to initialize variable with const

In C language objects with static storage duration have to be initialized with constant expressions or with aggregate initializers containing constant expressions.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
4

It is not about extern variables. In C variables with static storage have to have constant initializers. In C++ they may have almost any. The difference is: C++ objects have constructors and the object can be initialized almost any way (for example by the method or function call).

in C++ this kind of initialisation is possible:

#include <string.h>

volatile char s[] = "sdfsasdf";

size_t size = strlen((char *)s);
0___________
  • 60,014
  • 4
  • 34
  • 74
  • Only objects of class type have constructors. A `size_t` is not a class and does not have a constructor. The rest of what you say is true. – Lightness Races in Orbit Jan 05 '19 at 17:11
  • @LightnessRacesinOrbit yes it was simplification as the OPs question shows that he just started learning C, it is of course static initialisation and destruction in C++. But it does in the fact exactly the same – 0___________ Jan 05 '19 at 17:25
  • 1
    But it's not a "simplification", it's a wrong statement ;) Let's try to avoid teaching new starters falsehoods right out of the gate. – Lightness Races in Orbit Jan 05 '19 at 17:36