温馨提示×

linux c++怎么调用接口

小樊
41
2026-07-05 19:47:06
栏目: 编程语言

在 Linux 下用 C++ 调用接口,常见场景有几种,不同场景写法不一样。下面按最常见的几种情况给你一个清晰总结,并配上示例。


一、调用 系统调用(Linux API)

Linux 本身提供大量 C 接口(POSIX API),C++ 可以直接调用。

示例:打开文件(open / read / close)

#include <fcntl.h>
#include <unistd.h>
#include <iostream>

int main() {
    int fd = open("test.txt", O_RDONLY);
    if (fd < 0) {
        perror("open");
        return 1;
    }

    char buf[64];
    int n = read(fd, buf, sizeof(buf) - 1);
    if (n > 0) {
        buf[n] = '\0';
        std::cout << buf << std::endl;
    }

    close(fd);
    return 0;
}

编译:

g++ test.cpp -o test

✅ 特点:

  • 直接调用 Linux 提供的 C 接口
  • C++ 完全兼容 C

二、调用 动态库(.so)接口

这是 Linux 下最常见的“接口调用”。

1️⃣ 准备一个动态库

接口头文件 calc.h

#ifndef CALC_H
#define CALC_H

int add(int a, int b);

#endif

实现 calc.cpp

#include "calc.h"

int add(int a, int b) {
    return a + b;
}

编译成 .so

g++ -fPIC -shared calc.cpp -o libcalc.so

2️⃣ 调用动态库接口

调用程序 main.cpp

#include "calc.h"
#include <iostream>

int main() {
    std::cout << add(3, 5) << std::endl;
    return 0;
}

编译并链接

g++ main.cpp -o main -L. -lcalc

运行前设置库路径

export LD_LIBRARY_PATH=.
./main

✅ 特点:

  • 最常见
  • 接口通过头文件声明
  • -lxxx 链接 .so

三、使用 dlopen 动态加载接口(运行时调用)

适合插件、热更新、解耦架构。

示例

#include <dlfcn.h>
#include <iostream>

int main() {
    void* handle = dlopen("./libcalc.so", RTLD_NOW);
    if (!handle) {
        std::cerr << dlerror() << std::endl;
        return 1;
    }

    using AddFunc = int (*)(int, int);
    AddFunc add = (AddFunc)dlsym(handle, "add");

    if (!add) {
        std::cerr << dlerror() << std::endl;
        return 1;
    }

    std::cout << add(2, 3) << std::endl;

    dlclose(handle);
    return 0;
}

编译:

g++ main.cpp -o main -ldl

✅ 特点:

  • 不需要头文件
  • 运行时加载
  • 常用于插件系统

四、调用 网络接口(HTTP / REST)

Linux C++ 本身没有 HTTP 库,常用第三方库。

常见库

说明
libcurl 最常用
cpr 基于 curl 的 C++ 封装
boost.beast HTTP / WebSocket

示例:libcurl

#include <curl/curl.h>
#include <iostream>

int main() {
    curl_global_init(CURL_GLOBAL_DEFAULT);
    CURL* curl = curl_easy_init();

    curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
    curl_easy_perform(curl);

    curl_easy_cleanup(curl);
    curl_global_cleanup();
}

编译:

g++ test.cpp -o test -lcurl

五、调用 进程 / 管道接口

通过 systempopenfork + exec

#include <cstdlib>

int main() {
    system("ls -l");
}

六、总结对照表

场景 方式
Linux 系统接口 直接调用 C API
本地库接口 .so + 头文件
插件 / 动态加载 dlopen
网络接口 libcurl / boost
进程接口 system / exec

如果你能具体说一句:

“我想调用的是哪种接口?”

比如:

  • 调用 某个 SDK
  • 调用 第三方 so
  • 调用 HTTP 接口
  • 调用 内核接口
  • 调用 C 接口 / C++ 接口

我可以直接给你 针对你场景的完整示例

0