本教程演示如何在本地构建 libcc 并运行一个最小示例:创建一个异步事件管理器,注册一个 1 秒后触发的计时器,触发后打印日志并退出。
git、make 和常见编译工具链#include <stdio.h>
#include <libcc.h>
static bool_t timer_cb(_cc_async_event_t *async, _cc_event_t *e, const uint32_t which) {
if (which & _CC_EVENT_TIMEOUT_) {
_cc_logger_info(_T("[getting-started] timer fired, ident=%d, data=%ld"), e->ident, e->data);
/* 触发后停止事件循环 */
async->running = false;
return false; /* 返回 false 停止此定时器 */
}
return true;
}
int main(int argc, char **argv) {
_cc_async_event_t async;
_cc_event_t *ev;
/* 使用 select/kqueue/epoll 等初始化 async(根据平台自动选择) */
if (!_cc_register_kqueue(&async)) {
_cc_logger_error(_T("failed to register kqueue"));
return -1;
}
async.running = true;
/* 添加一个 1000ms 的定时器 */
ev = _cc_add_event_timeout(&async, 1000, timer_cb, 1);
if (!ev) {
_cc_logger_error(_T("failed to add timer"));
return -1;
}
/* 事件循环 */
while (async.running) {
async.wait(&async, 500);
}
/* 释放资源 */
async.free(&async);
return 0;
}
步骤概述:
git clone https://github.com/libcc/libcc.git
cd libcc
# 使用仓库自带构建脚本(会构建静态/动态库)
cd build
./build.sh debug
构建完成后,你可以把示例放到 tests,然后使用仓库的 Makefile / Xcode 工程编译,或手动编译并链接生成的库。
make .bin target=tests build=getting_stared
手动编译示例(通用说明):
下面是一个通用的手工编译命令(需根据你的 lib 输出目录和架构调整):
# 假设构建输出静态库位于 lib/x86_64 或 lib/arm64,库名为 libcc.a
# 调整 include/search path 与 -L/-l 参数以匹配你本地构建输出
gcc -Iinclude -Llib/x86_64 -lcc -lpthread tests/getting_started.c -o bin/getting_started
# 运行
./bin/getting_started
注意:
lib/arm64)。build/ 输出或使用 Xcode 打开 proj.OSX/cc.xcodeproj 来编译并调试。tests/ 并更新构建脚本,使其可直接通过 make 构建并运行。