快速入门
让我们从一个简单的 C 项目开始,体验 Catboy™ 构建系统的独特魅力。
创建 C 工程
本示例创建一个简单的 C 语言程序。程序包含一个自己的头文件,启动一个 POSIX 线程,并持续打印内容:
目录结构
c
.
├─ src/ # 源文件目录
│ └─ program.c # C 程序
├─ inc/ # 头文件目录
│ └─ custom.h # 头文件
└─ build.yaml # Catboy 构建蓝图代码内容
C 程序 src/program.c:
c
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include "custom.h"
// Thread function that will be executed by the new thread
void *thread_function(void* arg)
{
PRINT_MSG("Hello from the new thread!");
for (int i = 1; i <= 3; i++) {
printf("Thread: Count %d\n", i);
sleep(1);
}
PRINT_MSG("Thread finishing execution");
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t thread_id;
printf("Main: Creating thread...\n");
// Create a new thread
if (pthread_create(&thread_id, NULL, thread_function, NULL) != 0) {
fprintf(stderr, "Error creating thread\n");
return 1;
}
// Main thread continues execution
for (int i = 1; i <= 3; i++) {
printf("Main: Count %d\n", i);
sleep(1);
}
// Wait for the thread to finish
pthread_join(thread_id, NULL);
printf("Main: Thread completed, program exiting\n");
return 0;
}头文件 inc/custom.h:
c
#ifndef CUSTOM_H
#define CUSTOM_H
// Simple macro to print a formatted message
#define PRINT_MSG(msg) printf("[Thread Message]: %s\n", msg)
#endif // CUSTOM_H创建 Catboy 构建蓝图
Catboy 构建蓝图是一个 YAML 文件。在文件不用编写编译命令,而是声明式地指出需要编译的文件以及编译参数。
yaml
targets: # 编译目标声明开始
myapp: # 目标 myapp 声明开始
build: # 目标 myapp 的构建声明开始
type: executable # 构建类型: 可执行程序
sources: # 源代码列表声明开始
c: ["src/**/*.c"] # 包含 src 目录下所有 .c 文件 (递归搜索所有的子目录)
includes: ["inc"] # 头文件搜索路径 (-I) 添加项目目录下的 inc
links: ["pthread"] # 链接 pthread 线程库 (-l)
flags: ["-Wall", "-O2"] # 编译选项: 开启全部警告, 优化级别 2编译工程
在项目目录(即 build.yaml 所在目录)中,执行:
bash
catboy build编译成功有如下的输出:
Building target 'myapp' for platform 'native'
Build completed successfully in 84.722ms查看编译制品
Catboy 使用固定的编译制品的创建位置,路径为:
build/<目标>/<平台>/以本工程为例,编译后的目录结构为
c
.
├─ build/ # 编译生成目录
│ └─ myapp/ # 「myapp」目标的生成目录
│ └─ native/ # 「本机」平台生成目录
│ ├─ obj/ # 目标文件目录,内部结构与源文件结构一致
│ │ └─ src/
│ │ └─ program.o
│ └─ myapp # 编译制品:二进制程序
├─ src/ # 源文件目录
│ └─ program.c # C 程序
├─ inc/ # 头文件目录
│ └─ custom.h # 头文件
└─ build.yaml # Catboy 构建蓝图常用构建命令
以下是常用的构建命令:
编译工程
bash
catboy build [-v]加入 -v 可以显示详细的编译命令调用:
bash
$ catboy build -v
Building target 'myapp' for platform 'native'
/usr/bin/gcc -Wall -O2 -I/Users/catboy/Desktop/demo -Iinc -Ibuild/myapp -DCONFIG_TARGET_MYAPP -c src/program.c -o build/myapp/native/obj/src/program.o
/usr/bin/gcc build/myapp/native/obj/src/program.o -lpthread -o build/myapp/native/myapp
Build completed successfully in 72.27ms清理工程
bash
catboy clean重新构建工程
bash
catboy rebuild [-v]加入 -v 可以显示详细的编译命令调用。