You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Linux下将Bash脚本作为资源嵌入C++可执行程序并运行

如何在Linux下将Bash脚本作为资源嵌入C++可执行程序并运行

嘿,这事儿其实没那么复杂,我来给你一步步捋清楚怎么操作——核心思路就是把Bash脚本转成C++能识别的二进制数组嵌入程序里,运行时再把它临时存成可执行文件执行,用完顺手删掉就行。

第一步:整理项目结构

先把文件都摆好,比如你的项目目录可以是这样的:

helloworld_project/
├── CMakeLists.txt
└── src/
    ├── hello_world.cpp
    └── hello_world.sh

你的src/hello_world.sh内容就用你给的这个:

#!/bin/bash
echo "Hello World in hello_world.sh"

第二步:编写CMakeLists.txt

我们要用CMake调用系统自带的xxd工具,把脚本转成C语言头文件——xxd -i会自动把文件内容转成一个unsigned char数组,连数组长度变量都给你生成好,C++程序直接引用就行。

根目录的CMakeLists.txt这么写:

cmake_minimum_required(VERSION 3.10)
project(helloworld)

# 生成包含脚本二进制数据的头文件
add_custom_command(
    OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/hello_world_sh.h
    COMMAND xxd -i ${CMAKE_CURRENT_SOURCE_DIR}/src/hello_world.sh > ${CMAKE_CURRENT_BINARY_DIR}/hello_world_sh.h
    DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/hello_world.sh
    COMMENT "Generating header from bash script"
)

# 添加可执行文件,依赖生成的头文件
add_executable(helloworld 
    src/hello_world.cpp
    ${CMAKE_CURRENT_BINARY_DIR}/hello_world_sh.h
)

# 让编译器能找到生成的头文件
target_include_directories(helloworld PRIVATE ${CMAKE_CURRENT_BINARY_DIR})

第三步:编写C++代码

接下来写src/hello_world.cpp,它要做的就是把嵌入的脚本内容写到临时文件,给文件加执行权限,运行脚本,最后清理掉临时文件:

#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <sys/stat.h>
#include <unistd.h>
#include "hello_world_sh.h" // 这个是xxd生成的头文件

int main() {
    // 创建临时文件,用mkstemp比tmpnam更安全
    char temp_filename[] = "/tmp/embedded_script_XXXXXX";
    int fd = mkstemp(temp_filename);
    if (fd == -1) {
        perror("Failed to create temp file");
        return 1;
    }

    // 把嵌入的脚本内容写入临时文件
    ssize_t bytes_written = write(fd, hello_world_sh, hello_world_sh_len);
    if (bytes_written != hello_world_sh_len) {
        perror("Failed to write script to temp file");
        close(fd);
        remove(temp_filename);
        return 1;
    }
    close(fd);

    // 给临时文件加执行权限
    if (chmod(temp_filename, 0755) == -1) {
        perror("Failed to make script executable");
        remove(temp_filename);
        return 1;
    }

    // 运行脚本
    printf("Running embedded script:\n");
    int exit_code = system(temp_filename);
    if (exit_code == -1) {
        perror("Failed to run script");
        remove(temp_filename);
        return 1;
    }

    // 清理临时文件
    remove(temp_filename);

    return WEXITSTATUS(exit_code);
}

第四步:编译和运行

现在到项目根目录,执行下面的命令编译:

mkdir build && cd build
cmake ..
make

编译完成后,运行生成的可执行文件:

./helloworld

你就能看到想要的输出了:

Running embedded script:
Hello World in hello_world.sh

这样就搞定啦!整个脚本完全嵌入到可执行文件里,不用额外携带脚本文件就能直接运行。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 13:43:07