Skip to content
On this page

clang_extern关键字


标签:clang/basic  

extern 关键字可以声明一个其他文件中的全局变量或者全局函数,在本文件中直接调用使用。

c
// 文件1: main.c
#include <stdio.h>

// 声明全局变量 globalVariable,定义在其他文件中
extern int globalVariable;

extern void function();  // 声明函数 function,定义在其他文件中

int main() {
    printf("globalVariable: %d\n", globalVariable);
    function();
    return 0;
}
c
// 文件2: other.c
int globalVariable = 10;  // 定义全局变量 globalVariable

void function() {
    printf("This is the function.\n");
}

和使用 #include 的区别是,它不是在预编译阶段处理的,所以编译器会跳过对变量类型和函数使用的检查,直接在链接阶段进行编译后代码的链接。

Last updated: