我正在使用c18编译器,我在project.h中声明了外部变量x
并在
project.h
extern unsigned int x;
Run Code Online (Sandbox Code Playgroud)
在file1.c
#include"project.h"
foo1()
{
x=200;
}
Run Code Online (Sandbox Code Playgroud)
并在foo2.c
#include"project.h"
foo2()
{
printf("%d",x);
}
Run Code Online (Sandbox Code Playgroud)
foo1首先在foo2之前执行我在project.h中进行了extern声明,我在foo1.c中定义了x
如果foo2.c必须有200作为x值正确.?
如果这两个文件加上一个只包含的标题extern int x;,你就拥有它,它甚至不应该编译(好吧,它可能会编译,但它不会链接).
extern int x;让编译器知道它x存在于某处,但实际上并不存在.
通常这样做的方法是在某处定义变量并在任何地方声明它,例如:
project.h:
extern int x; // declare
file1.c:
#include "project.h" // declare in the header
int main (void) {
x = 200;
printf ("x is %d\n", x);
return 0;
}
file2.c:
#include "project.h" // declare in the header
int x; // define it.
Run Code Online (Sandbox Code Playgroud)