5

The following piece of code working fine:

#include <stdio.h>

extern int foo; // Without constant
int foo = 42;

int main() 
{
    printf("%d\n",foo);
    return 0;
}

But, the following piece of code give an error:

#include <stdio.h>

const extern int foo; // With constant
int foo = 42;

int main() 
{
    printf("%d\n",foo);
    return 0;
}

So, why does const extern give an error?

msc
  • 33,420
  • 29
  • 119
  • 214

3 Answers3

6

Standard says:
C11-§6.7/4

All declarations in the same scope that refer to the same object or function shall specify compatible types

const int and int are not compatible for the same object foo in the same scope.

haccks
  • 104,019
  • 25
  • 176
  • 264
4

These two declarations are contradictory:

const extern int foo; // With constant
int foo = 42;

The first one declares foo as const, and the second one declares it as non const.

Error messages:

prog.cpp:4:5: error: conflicting declaration
   ‘int foo’ int foo = 42; 
         ^~~
 prog.cpp:3:18: note: previous declaration as ‘const int foo’
    const extern int foo; // With constant 
                     ^~~
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
3

You say foo is const and then try to change its constness with the other declaration. Do this and you should be fine.

  const extern int foo; // With constant
  const int foo = 42;
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
  • I'm afraid this is not what the OP does: `int foo = 42;` is not a modification of `foo`, it is a declaration with an initializer. The problem is the definitions are incompatible. `const volatile int foo = 42;` would have been an error too. – chqrlie Jul 06 '17 at 07:14
  • Surprisingly, `static const int foo = 42;` would be compatible. – chqrlie Jul 06 '17 at 07:15
  • @chqrlie Correct.Thanks.Please feel free to edit this answer if its still wrongly worded. – Gaurav Sehgal Jul 06 '17 at 07:26