在 Linux 下用 C++ 调用接口,常见场景有几种,不同场景写法不一样。下面按最常见的几种情况给你一个清晰总结,并配上示例。
Linux 本身提供大量 C 接口(POSIX API),C++ 可以直接调用。
#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 下最常见的“接口调用”。
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;
}
.sog++ -fPIC -shared calc.cpp -o libcalc.so
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适合插件、热更新、解耦架构。
#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
✅ 特点:
Linux C++ 本身没有 HTTP 库,常用第三方库。
| 库 | 说明 |
|---|---|
| libcurl | 最常用 |
| cpr | 基于 curl 的 C++ 封装 |
| boost.beast | HTTP / WebSocket |
#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
通过 system、popen 或 fork + exec
#include <cstdlib>
int main() {
system("ls -l");
}
| 场景 | 方式 |
|---|---|
| Linux 系统接口 | 直接调用 C API |
| 本地库接口 | .so + 头文件 |
| 插件 / 动态加载 | dlopen |
| 网络接口 | libcurl / boost |
| 进程接口 | system / exec |
如果你能具体说一句:
“我想调用的是哪种接口?”
比如:
我可以直接给你 针对你场景的完整示例。