C++的内外部连接
内外部连接
在C++中,有两种连接方式:内连接和外连接。 这样区分有助于帮助我们进行整体项目的管理 内连接就像是自己文件内部可见的
内连接
桑婆
const int a = 10;
static int b = 20;
static int add(int x, int y) {
return x + y;
}
inline bool is_prime(int n) {
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
// 匿名的命名空间
namespace {
int z = 30; // 内部链接,仅当前文件可见
}
内连接不会与其他文件的同名符号冲突。 适用于仅在当前文件使用的变量/函数。
外连接
// main.cpp
#include <iostream>
using namespace std;
// 直接声明函数
extern int add(int a, int b);
int main() {
int x = 10, y = 20;
cout << "The sum of " << x << " and " << y << " is " << add(x, y) << endl;
return 0;
}
引用了同个文件目录下的a.cpp里面的add函数
int add(int a, int b){
return a+b;
}
一般这么写编译器会通过不了,显示
E:/Blogs/15/main.cpp:9: undefined reference to `add(int, int)’ collect2.exe: error: ld returned 1 exit status
通常需要两个文件通过命令的方式进行编译
g++ main.cpp a.cpp -o myprogram
外部链接的符号可以被其他编译单元(.cpp 文件)访问,通常用于全局共享变量或函数
int g_x = 100; // 非static的全局变量,外部链接,其他文件可访问
void func() { } // 非static的全局函数,外部链接,其他文件可访问
extern int g_y; // 外部链接,声明(定义在其他文件)
class MyClass { }; // 外部链接
template<typename T> // 外部链接
void tmplFunc() { }
inline int g_z = 300; // 外部链接(C++17)
Enjoy Reading This Article?
Here are some more articles you might like to read next:
- Google Gemini updates: Flash 1.5, Gemma 2 and Project Astra
- Displaying External Posts on Your al-folio Blog
- Graph RAG with Milvus —— 纯向量库造图的多跳推理
- Hierarchical Indices 层级索引 —— 先粗后细的两级检索
- HyDE 与 HyPE —— 假设检索技术的两个方向
- 二叉树刷题总结
- RAG 技术体系化分类——从 Pipeline 阶段到失败模式
- MemoRAG 记忆增强型 RAG 总结
- Microsoft GraphRAG 基于知识图谱的 RAG 总结
- Multimodal RAG with Captioning 图像描述型多模态 RAG 总结