我想定义程序使用的外部全局符号(const char*)。在链接时添加具有给定值的符号。例如,这对于提交哈希或构建时间很有用。

我发现--defsym还有其他功能。 Go链接器通过-X选项支持此功能。 (是的,我知道,Go字符串是托管的,但是我说的是普通的旧的零终止的c字符串)

例如:

extern const char *git_commit;

int main(int argc, char *argv[]) {
    puts(git_commit);
    return 0;
}


gcc main.o -Wl<something here that adds git_commit and set it to '84e5...'>


我知道config.h方法并建立包含这些字符串的目标文件。但它的2019年就知道了。这样简单的任务应该很容易。

编辑更精确的问题
gcc / binutils中是否有与Go Linker的-X选项等效的选项。

最佳答案

编译/预处理时间有所变化,请考虑以下几点:

#include <stdio.h>

const char * git_commit = GIT_COMMIT;

int main(int argc, char ** argv) {
        puts(git_commit);
        return 0;
}


并在命令行中:

gcc -o test test.c -DGIT_COMMIT="\"This is a test\""

假设您使用的是GCC编译器。

10-01 00:07
查看更多