error: extern declaration of 'i' follows declaration with no linkage

前端 未结 3 1596
心在旅途
心在旅途 2020-12-07 03:39

In the following program, I thought that extern int i; will change the following i to refer to the i defined outside main

相关标签:
3条回答
  • 2020-12-07 04:13

    Once you define a variable named i inside your main function, the i at file scope is masked and cannot be accessed (unless you have its address).

    When you later add the declaration extern int i, this conflicts with the local variable named i at the same scope since locals can't have external linkage. It does not give you access to the global i.

    When you remove the local i, the extern int i declaration matches up with the definition at file scope, so there is no error. As for the warning on extern int i=1;, that did not go away for me on gcc 4.1.2, so that depends on the compiler.

    0 讨论(0)
  • 2020-12-07 04:19
    #include <stdio.h>
    
    int i=1;  // external variable
    
    int main()
    {
        int i=2;            // local variable
        printf("%d\n", i);  // print local variable i==2
    
        {
        extern int i;       // point to external variable
        printf("%d\n", i);  // print external variable i==1
        }
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-07 04:37

    Question: What is the reason of the "error: extern declaration of 'i' follows declaration with no linkage", where "declaration with no linkage" refers to int i=2;?
    Answer: We do not need to use the extern keyword here on line 3 when it is a single file in a program and there is no other file in the same program or other location on the same file where the variable int i has its definition. There are two main reasons we can use extern keyword in C:
    1. When we want to declare a variable explicitly/globally but without its definition.
    2. To make the variable globally visible from any other file in a multi-file program or other location of the same file (see Ihdina's exmaple for this scenario).
    Compiling your code on my system I get the following error,
    error: extern declaration of 'i' follows non-extern declaration . which totally makes sense that the compiler detects the extern on line 9 as a duplicate declaration of the same variable int i on line 7.

    Question: After I remove int i=2 in main, the error is gone, the warning "warning: 'i' initialized and declared 'extern'" on extern int i=1; also disappear . Why is that?
    Answer: After removing the int i=2; the error was gone on my system but still I have the following warning message:
    warning: 'extern' variable has an initializer [-Wextern-initializer] Basically my system (Apple LLVM version 8.1.0 (clang-802.0.42)) does not like the explicit initialization with extern keyword. So, you should modify your code as per Ihdina's answer which compiles without error.

    0 讨论(0)
提交回复
热议问题