文章目录
extern 和 extern “C”
1 目标
本文的目的了解extern 和 extern "C"的用法。
2 代码
2.1 extern
extern 关键字在 C++ 中有多个用途,主要用于声明变量或函数的外部链接,以便在多个文件之间共享数据或函数。
2.1.1 使用 extern 声明全局变量
假设我们有两个文件 main.cpp 和 globals.cpp,我们希望在 main.cpp 中使用 globals.cpp 中定义的全局变量。
- globals.cpp
// globals.cpp
#include <iostream>
int globalVar = 42; // 定义全局变量
void printGlobalVar() {
std::cout << "Global variable: " << globalVar << std::endl;
}
- main.cpp
// main.cpp
#include <iostream>
// 使用 extern 声明在其他文件中定义的全局变量
extern int globalVar;
void printGlobalVar(); // 声明在其他文件中定义的函数
int main() {
std::cout << "Initial global variable: " << globalVar << std::endl;
globalVar = 100; // 修改全局变量的值
printGlobalVar(); // 调用在其他文件中定义的函数
return 0;
}
2.1.2 使用 extern 声明函数
假设我们有两个文件 main.cpp 和 functions.cpp,我们希望在 main.cpp 中调用 functions.cpp 中定义的函数
- functions.cpp
// functions.cpp
#include <iostream>
void sayHello() {
std::cout << "Hello from functions.cpp!" << std::endl;
}
- main.cpp
// main.cpp
#include <iostream>
// 使用 extern 声明在其他文件中定义的函数
extern void sayHello();
int main() {
sayHello(); // 调用在其他文件中定义的函数
return 0;
}
2.1.3 在头文件中使用 extern
为了便于维护和使用,通常会将 extern 声明放在头文件中,然后在多个源文件中包含这个头文件。
- globals.h
// globals.h
#ifndef GLOBALS_H
#define GLOBALS_H
extern int globalVar; // 使用 extern 声明全局变量
void printGlobalVar(); // 声明函数
#endif
- globals.cpp
// globals.cpp
#include "globals.h"
#include <iostream>
int globalVar = 42; // 定义全局变量
void printGlobalVar() {
std::cout << "Global variable: " << globalVar << std::endl;
}
- main.cpp
// main.cpp
#include <iostream>
#include "globals.h"
int main() {
std::cout << "Initial global variable: " << globalVar << std::endl;
globalVar = 100; // 修改全局变量的值
printGlobalVar(); // 调用在其他文件中定义的函数
return 0;
}
2.2 extern “C”
C++ 和 C 的名称修饰(name mangling)机制不同。C++ 编译器为了支持函数重载,会在编译时修改函数的名称,而 C 编译器不会。因此,当你在 C++ 中调用 C 函数或从 C 调用 C++ 函数时,必须使用 extern “C” 以确保链接器能够正确地找到这些函数。
说句大白话就是为了防止编译器给函数改名
2.2.1 在 C++ 中调用 C 函数
- my_c_functions.c
// my_c_functions.c
#include <stdio.h>
void sayHello() {
printf("Hello from C!\n");
}
- my_c_functions.h
// my_c_functions.h
#ifndef MY_C_FUNCTIONS_H
#define MY_C_FUNCTIONS_H
#ifdef __cplusplus
extern "C" {
#endif
void sayHello();
#ifdef __cplusplus
}
#endif
#endif
- main.cpp
// main.cpp
#include <iostream>
#include "my_c_functions.h"
int main() {
sayHello(); // 调用 C 函数
return 0;
}
2.2.2 在 C 中调用 C++ 函数
- my_cpp_functions.cpp
// my_cpp_functions.cpp
#include <iostream>
extern "C" void sayHelloFromCpp() {
std::cout << "Hello from C++!" << std::endl;
}
- my_cpp_functions.h
// my_cpp_functions.h
#ifndef MY_CPP_FUNCTIONS_H
#define MY_CPP_FUNCTIONS_H
#ifdef __cplusplus
extern "C" {
#endif
void sayHelloFromCpp();
#ifdef __cplusplus
}
#endif
#endif
- main.c
// main.c
#include "my_cpp_functions.h"
int main() {
sayHelloFromCpp(); // 调用 C++ 函数
return 0;
}