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

Apple Silicon(M2 Max)下C语言使用OpenSSL SHA1的链接问题

问题

我正在开发一个Git克隆工具,目前在实现hash-file命令,尝试通过C语言调用OpenSSL的SHA1计算已知字符串的哈希值,编写了如下代码:

#include <openssl/sha.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int hashFile(char *file_name, int ww) {
    int i, ret;
    size_t size_len;
    unsigned long file_size;
    char path[56];
    unsigned char hash[SHA_DIGEST_LENGTH];
    char *token, *type, *blob_content, *content;

    FILE *src = fopen(file_name, "r");
    if (ferror(src)) {
        perror("Unable to read file");
        return 1;
    }
    fseek(src, 0L, SEEK_END);
    file_size = ftell(src);
    rewind(src);
    size_len = snprintf(NULL, 0, "%lu", file_size);

    char *buffer = (char *)malloc((size_t)file_size + 1);
    fread(buffer, sizeof(char), file_size, src);
    buffer[file_size] = '\0';

    blob_content = (char *)malloc((7 + sizeof(unsigned long) + file_size + 1) *
                                  sizeof(char));
    snprintf(blob_content, 7 + size_len + 1, "blob %lu\\0", file_size);
    strcat(blob_content, buffer);

    SHA1((unsigned char *)blob_content, strlen(blob_content), hash);
    printf("%s\n", hash);

    free(blob_content);
    free(buffer);

    return 0;
}

void printHashHelp() {
    printf("usage: twat hash-file [options] <file_name>\n");
    printf("\n");
    printf("options:\n");
    printf("\t-w: write contents to objects store\n");
}

执行编译命令时出现链接错误:

$ clang --std=c17 -fmodules -fprebuilt-module-path=. -I/opt/homebrew/opt/openssl/include cmd.c comp.c init.c cat.c hash.c -o twat -v
...
Undefined symbols for architecture arm64:
  "_SHA1", referenced from:
      _hashFile in hash-fc3ff3.o
ld: symbol(s) not found for architecture arm64

尝试过多种链接openssl/sha.h的方法但未解决问题,请问在M2 Max上应如何正确链接并启用SHA1?正确的clang命令是什么?

解决方法

核心原因

编译时仅通过-I指定了OpenSSL的头文件路径,但未链接OpenSSL的库文件,导致链接器找不到SHA1函数的具体实现。

正确的Clang编译命令

在M2 Max(arm64架构)上,Homebrew安装的OpenSSL库默认路径为/opt/homebrew/opt/openssl/lib,需要通过-L指定库路径,再通过-lcrypto链接OpenSSL的加密库(SHA1属于libcrypto组件):

clang --std=c17 -fmodules -fprebuilt-module-path=. -I/opt/homebrew/opt/openssl/include -L/opt/homebrew/opt/openssl/lib -lcrypto cmd.c comp.c init.c cat.c hash.c -o twat -v

额外补充

  1. 自定义库路径验证:若你的OpenSSL不是通过Homebrew安装,可执行openssl version -a查看实际库路径,替换命令中的-L参数值。
  2. SHA1兼容性处理:OpenSSL 3.x中SHA1被标记为弱算法,编译时可能出现警告,可添加-Wno-deprecated-declarations选项屏蔽,或考虑改用SHA256等更安全的哈希算法。
  3. 代码输出修正:当前代码中printf("%s\n", hash);会输出乱码,因为hash是二进制字节数组,需转为十六进制字符串输出,示例代码:
for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
    printf("%02x", hash[i]);
}
printf("\n");

内容的提问来源于stack exchange,提问作者h5law

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 09:35:07