构建并运行第一个示例

本教程演示如何在本地构建 libcc 并运行一个最小示例:创建一个异步事件管理器,注册一个 1 秒后触发的计时器,触发后打印日志并退出。

先决条件

  • macOS(或 Linux),命令行工具(Xcode Command Line Tools)查看:Build tools提供详细说明方法
  • 已安装 gitmake 和常见编译工具链
  • 仓库已 clone 到本地(见下方“构建并安装”)

示例代码:

#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;
}

构建并运行(macOS / zsh)

步骤概述:

  1. 先构建 libcc(使用仓库已有脚本):
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

注意:

  • 在 macOS Apple Silicon 机器上,请使用对应的架构目录(例如 lib/arm64)。
  • 若找不到 libcc 静态库,请查看 build/ 输出或使用 Xcode 打开 proj.OSX/cc.xcodeproj 来编译并调试。

下一步

  • 完成并运行示例后,可继续查看:事件循环TCP 服务端/客户端示例HTTP/WS 示例等教程。
  • 若你希望,我可以把该示例自动加入到仓库的 tests/ 并更新构建脚本,使其可直接通过 make 构建并运行。