我编写了以下代码
head.h
int i = 0;
示例.cpp
#include <stdio.h>
#include "head.h"
extern int i;
i = 20;
int main() {
printf("%d n",i);
return 0;
}
当我编译sample.cpp时,编译器抛出以下错误:
sample.c:5:1: warning: data definition has no type or storage class [enabled by default]
sample.c:5:1: error: redefinition of ‘i’
head.h:1:5: note: previous definition of ‘i’ was here
相反,extern
声明应该在实现文件的头和定义中,并且只定义一次。
//head.h
extern int i;
//sample.cpp
#include <stdio.h>
#include "head.h"
int i = 20;
int main() {
printf("%d n",i);
return 0;
}
您可以根据需要多次声明变量,但定义必须是唯一的。