# 构建实时程序(手动启动)

### Makefile 示例

    # 交叉编译器设置
    CC := $(X_GCC_ROOT_PATH)/bin/x86_64-sinsegye-linux-gnu-gcc
    CXX := $(X_GCC_ROOT_PATH)/bin/x86_64-sinsegye-linux-gnu-g++
    SYSROOT := $(X_GCC_ROOT_PATH)/x86_64-sinsegye-linux-gnu/sysroot

    # 目录设置
    SRC_DIR := src
    BUILD_DIR := build
    BIN_DIR := bin

    # 构建文件选择
    SOURCES := $(wildcard $(SRC_DIR)/*.c)
    OBJECTS := $(patsubst $(SRC_DIR)/%.c,$(BUILD_DIR)/%.o,$(SOURCES))
    TARGET := $(BIN_DIR)/hello

    # 编译选项
    CFLAGS := --sysroot=$(SYSROOT) -I$(SYSROOT)/usr/include
    LDFLAGS := --sysroot=$(SYSROOT) -L$(SYSROOT)/usr/lib -L$(SYSROOT)/lib64 \
              $(CUSTOM_LIBS)
              -Wl,--no-as-needed -Wl,@$(SYSROOT)/usr/lib64/cobalt.wrappers \
              -Wl,@$(SYSROOT)/usr/lib64/modechk.wrappers \
              -Wl,--dynamic-list=$(SYSROOT)/usr/lib64/dynlist.ld \
              -lcobalt -lmodechk -lm -ldl -lrt -lpthread

    # Rules
    .PHONY: all clean

    all: $(TARGET)

    $(TARGET): $(OBJECTS) | $(BIN_DIR)
            $(CC) $(LDFLAGS) -o $@ $^

    $(BUILD_DIR)/%.o: $(SRC_DIR)/%.c | $(BUILD_DIR)
            $(CC) $(CFLAGS) -o $@ -c $<

    $(BIN_DIR) $(BUILD_DIR):
            mkdir -p $@

    clean:
            rm -rf $(BUILD_DIR) $(BIN_DIR)

    # End of Makefile

### 实时应用程序示例

    #include <pthread.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <string.h>
    #include <sched.h>

    // 线程函数
    void* thread_function(void* arg) {
        char thread_name[16];
        pthread_getname_np(pthread_self(), thread_name, sizeof(thread_name));
        printf("Thread %s is running with FIFO scheduling, priority 88\n", thread_name);

        // 执行一些工作
        for (int i = 0; i < 500; i++) {
            printf("Thread %s is working...\n", thread_name);
            sleep(1); // 模拟工作
        }

        return NULL;
    }

    int main() {
        pthread_t thread_id;
        pthread_attr_t attr;
        struct sched_param param;

        // 初始化线程属性
        pthread_attr_init(&attr);

        // 设置线程调度策略为 FIFO
        pthread_attr_setschedpolicy(&attr, SCHED_FIFO);

        // 设置线程优先级
        param.sched_priority = 88;
        pthread_attr_setschedparam(&attr, &param);

        // 允许设置调度策略和参数
        pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);

        // 创建线程
        pthread_create(&thread_id, &attr, thread_function, NULL);
        pthread_setname_np(thread_id, "WorkerThread");

        // 等待线程结束
        pthread_join(thread_id, NULL);

        // 销毁线程属性对象
        pthread_attr_destroy(&attr);

        printf("Main thread is done.\n");
        return 0;
    }

### 交叉编译

#### 步骤 1

进入到demo_project目录

    cd C:\Users\someone\Desktop\demo_project

#### 步骤 2

确定交叉编译器工具链路径，假设交叉编译器路径为`C:\Users\someone\Desktop\xgcc\x86_64-sinsegye-linux-gnu`

### 步骤 3

    make X_GCC_ROOT_PATH=C:\Users\someone\Desktop\xgcc\x86_64-sinsegye-linux-gnu