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: