无法编辑外部变量

时间:2012-09-11 17:25:39

标签: c++ extern

我写了以下代码

head.h

int i = 0;

sample.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

1 个答案:

答案 0 :(得分:5)

反过来说,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;
}

您可以根据需要声明变量,但定义必须是唯一的。