开发者

Whats the error in the C code?

开发者 https://www.devze.com 2023-04-04 03:27 出处:网络
I have a code like this: #include<stdio.h> int main() { extern int i; i = 20; printf(\"%d\\n\", sizeof(i));

I have a code like this:

#include<stdio.h>
int main()
{
    extern int i;
    i = 20;
    printf("%d\n", sizeof(i));
    return 开发者_运维百科0;
}

I get an error like this:

In function `main':
undefined reference to `i'

Even though I have defined i why there is an error thrown? Thanks in advance.


You have declared i to be defined in a separate file, but haven't linked to an external file.

If you remove the extern keyword, this will work as you expect.


The extern keyword declares a variable or function and specifies that it has external linkage (its name is visible from files other than the one in which it's defined). When modifying a variable, extern specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends). The variable or function may be defined in another source file, or later in the same file. Declarations of variables and functions at file scope are external by default.

Where is i defined?

Try this.

#include<stdio.h>
int main()
{
  int i;
  i = 20;
  printf("%d\n", sizeof(i));
  return 0;
}


The "extern" keyword is you telling the compiler "This variable is define somewhere else, just use it and trust me that it will be available at linking time."

0

精彩评论

暂无评论...
验证码 换一张
取 消