外部声明中的警告

rea*_*ays 8 c

我在temp2.​​h中声明了一个变量i,它只 extern i; 包含一行上面的行,并创建了另一个文件temp3.c

 #include<stdio.h>
#include<temp2.h>
int main ()
{
extern i;
i=6;
printf("The i is %d",i);
}
Run Code Online (Sandbox Code Playgroud)

当我在上面编译时, cc -I ./ temp3.c 我得到了以下错误

 /tmp/ccJcwZyy.o: In function `main':
temp3.c:(.text+0x6): undefined reference to `i'
temp3.c:(.text+0x10): undefined reference to `i'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

我在上面的temp3.c中声明了extern,正如我在上面的文章中提到的那样,KR第33页说.我为temp3.c尝试了另一种方法,使用相同的头文件temp2.​​h

 #include<stdio.h>
#include<temp2.h>
int main ()
{

i=6;
printf("The i is %d",i);
}
Run Code Online (Sandbox Code Playgroud)

并编译它 cc -I ./ temp3.c 并得到以下错误

/tmp/ccZZyGsL.o: In function `main':
temp3.c:(.text+0x6): undefined reference to `i'
temp3.c:(.text+0x10): undefined reference to `i'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

我也试过了

 #include<stdio.h>
#include<temp2.h>
int main ()
{
extern i=6;
printf("The i is %d",i);
} 
Run Code Online (Sandbox Code Playgroud)

汇编了这一个

 cc -I ./ temp3.c
Run Code Online (Sandbox Code Playgroud)

得到与第1篇相同的错误

 temp3.c: In function ‘main’:
temp3.c:5: error: ‘i’ has both ‘extern’ and initializer
Run Code Online (Sandbox Code Playgroud)

所以我尝试了至少3种不同的方式来使用extern,但是没有使用它们.

Pra*_*rav 15

当您使用声明变量时extern,您告诉编译器变量是在别处定义的,并且定义将在链接时提供.包容是一个完全不同的东西.

extern

外部变量必须在任何函数之外定义一次; 这为它预留了存储空间.必须在每个想要访问它的函数中声明变量; 这说明了变量的类型.声明可以是明确的外部声明,也可以是上下文隐含的.

- C编程语言

必须在程序的一个模块(在一个翻译单元中)中定义一个变量.如果没有定义或多于一个定义,则可能在链接阶段产生错误(如示例1和2中所示).

尝试以下内容

a.c

int i =10; //definition
Run Code Online (Sandbox Code Playgroud)

b.c

extern int i; //declaration
int main()
{
    printf("%d",i);
}
Run Code Online (Sandbox Code Playgroud)

使用编译,链接和创建可执行文件

gcc a.c b.c -o executable_name
Run Code Online (Sandbox Code Playgroud)

要么


gcc -c a.c // creates a.o
gcc -c b.c // creates b.o
Run Code Online (Sandbox Code Playgroud)

现在链接目标文件并创建可执行文件

gcc a.o b.o -o executable_name
Run Code Online (Sandbox Code Playgroud)