c中外部变量的使用
Use of extern variable in c
我在 c 中制作了两个文件,即 file1.c
file2.c
。在 file1.c 我写了
#include< stdio.h >
int s=10;
void main()
{
printf("This is file 1");
}
在file2.c
include < stdio.h >
extern int s;
void main() {
printf("%d",s);
}
当我在 ubuntu 终端中编译 file2.c 时,出现 undefined referenced
to s 错误。
我该如何解决这个错误?
第二种情况,
extern int s;
告诉编译器 "somewhere there" 存在一个类型为 int
的变量 s
,但它实际上并不 "define" 变量。所以,链接器不知道在哪里可以找到变量,它找不到变量并抛出错误。
您需要在单独的翻译单元(使用 extern
的目的)或同一翻译单元(如果需要)中定义变量。
在file1.c
#include <stdio.h>
void myfunction( void );
int s=10;
void myfunction()
{
printf("This is file 1");
}
在file2.c
#include <stdio.h>
void myfunction( void );
extern int s;
int main( void )
{
myfunction();
printf("%d",s);
}
然后编译(示例使用gcc
gcc -g -Wall -Wextra -pedantic -Wconversion -std=gnu11 -c file1.c -o file1.o
gcc -g -Wall -Wextra -pedantic -Wconversion -std=gnu11 -c file2.c -o file2.o
然后 link 使用:
gcc -g file1.o file2.o -o myexec
然后运行它作为
./myexec
当然,如果你使用Visual Studio,命令行语句会略有不同
我在 c 中制作了两个文件,即 file1.c
file2.c
。在 file1.c 我写了
#include< stdio.h >
int s=10;
void main()
{
printf("This is file 1");
}
在file2.c
include < stdio.h >
extern int s;
void main() {
printf("%d",s);
}
当我在 ubuntu 终端中编译 file2.c 时,出现 undefined referenced
to s 错误。
我该如何解决这个错误?
第二种情况,
extern int s;
告诉编译器 "somewhere there" 存在一个类型为 int
的变量 s
,但它实际上并不 "define" 变量。所以,链接器不知道在哪里可以找到变量,它找不到变量并抛出错误。
您需要在单独的翻译单元(使用 extern
的目的)或同一翻译单元(如果需要)中定义变量。
在file1.c
#include <stdio.h>
void myfunction( void );
int s=10;
void myfunction()
{
printf("This is file 1");
}
在file2.c
#include <stdio.h>
void myfunction( void );
extern int s;
int main( void )
{
myfunction();
printf("%d",s);
}
然后编译(示例使用gcc
gcc -g -Wall -Wextra -pedantic -Wconversion -std=gnu11 -c file1.c -o file1.o
gcc -g -Wall -Wextra -pedantic -Wconversion -std=gnu11 -c file2.c -o file2.o
然后 link 使用:
gcc -g file1.o file2.o -o myexec
然后运行它作为
./myexec
当然,如果你使用Visual Studio,命令行语句会略有不同