C++ extern(八股总结)

定义

用于声明变量或函数的外部链接性,使它们的定义可能在另一个文件或作用域中。

作用

1. 与C连用

当它与"C"一起连用时,如: extern "C" void fun(int a, int b);则告诉编译器在编译fun这个函数名时按着C的规则去翻译相应的函数名而不是C++的;

示例:

C 文件: c_function.c

c++ 复制代码
#include <stdio.h>

void hello() {
    printf("Hello from C function\n");
}

C++ 文件: main.cpp

c++ 复制代码
#include <iostream>

extern "C" void hello(); // 告诉编译器这是一个 C 函数

int main() {
    hello(); // 调用 C 函数
    return 0;
}

2.声明函数和变量

当它作为一个对函数或者全局变量的外部声明,提示编译器遇到此变量或函数时,在其它模块中寻找其定义。

假设有两个文件:

文件1: file1.cpp

c++ 复制代码
#include <iostream>
using namespace std;

int globalVar = 42; // 定义全局变量

void printVar() {
    cout << "Global variable: " << globalVar << endl;
}

文件2: file2.cpp

C++ 复制代码
#include <iostream>
using namespace std;

// 声明外部变量
extern int globalVar;

// 声明外部函数
extern void printVar();

int main() {
    printVar(); // 调用 file1.cpp 中的函数
    cout << "Global variable in main: " << globalVar << endl;
    return 0;
}

编译并链接:

C++ 复制代码
g++ file1.cpp file2.cpp -o output
./output

输出:

C++ 复制代码
Global variable: 42
Global variable in main: 42
相关推荐
Tiandaren1 小时前
Selenium 4 教程:自动化 WebDriver 管理与 Cookie 提取 || 用于解决chromedriver版本不匹配问题
selenium·测试工具·算法·自动化
nbsaas-boot2 小时前
Java 正则表达式白皮书:语法详解、工程实践与常用表达式库
开发语言·python·mysql
岁忧2 小时前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_7892 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
风无雨2 小时前
GO 启动 简单服务
开发语言·后端·golang
斯普信专业组2 小时前
Go语言包管理完全指南:从基础到最佳实践
开发语言·后端·golang
秋说4 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy4 小时前
力扣61.旋转链表
算法·leetcode·链表
我是苏苏4 小时前
C#基础:Winform桌面开发中窗体之间的数据传递
开发语言·c#
斐波娜娜4 小时前
Maven详解
java·开发语言·maven