0

我写了以下代码

头文件

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
4

1 回答 1

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;
}

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

于 2012-09-11T17:26:58.100 回答