c - 我不明白 "extern"

标签 c

<分区>

7.h:

int a

5.c:

#include"7.h"
#include <stdio.h>
int b;
void way();
void way() {
printf("%p\n",&b);
}

6.c:

#include "7.h"
#include <stdio.h>
void way();
int b;
int main(int argc, char const *argv[])
{
way();
printf("%p\n",&b);
return 0;
}

为什么我用“gcc -std=c90 5.c 6.c”可以编译成功!

结果是 0x10288b018 0x10288b018

相同的地址!!!!!!但我不使用 extern !为什么!

但我将“6.c”更改为:

6.c:

 #include "7.h"
#include <stdio.h>
void way();
int b=8;
int main(int argc, char const *argv[])
{
way();
printf("%p\n",&a);
return 0;
}

5.c 到:

#include"7.h"
#include <stdio.h>
int b=5;
void way();
void way() {
printf("%p\n",&a);
}

但是结果是:

duplicate symbol _b in:
    /var/folders/sb/dc6wxwf16kl7k1wrhrxjx5j40000gn/T/5-00d5c1.o
    /var/folders/sb/dc6wxwf16kl7k1wrhrxjx5j40000gn/T/6-2b050b.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

最佳答案

extern 关键字不是必需的。根据 C99 标准:

6.7.5.3.17: If the declaration occurs outside of any function, the identifiers have file scope and external linkage.

第 6.9.2.4 节解释了您的两个示例之间的区别:

int i1 = 1; // definition, external linkage
int i4;     // tentative definition, external linkage

标准说 i1 是一个定义,而 i4 是一个暂定 定义。有多个定义是错误的;有多个暂定定义不是。

如果实体有非暂定定义,则所有暂定定义均引用该实体;否则,多个暂定定义指的是同一个实体。

关于c - 我不明白 "extern",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40318037/

相关文章:

c - openssl命令行解密aes ctr 128

c - Windows 和 Linux (gcc) C 编译器中的不同输出

c - 删除链表中的连续元素

c - 指向字符串字符的指针数组

c - 如何根据调用的函数使用 errno

c++ - 在 Linux 32 位上带有基数 36 的 strtoull 溢出 unsigned long long

c++ - 从 gcc 函数树节点检索函数参数

c - 使用 fscanf 读取逗号分隔的 double

c - 通过滑动窗口协议(protocol)进行数据转换,C

通过 fifo 队列 linux 进行通信