go cgo编译错误

1 . gcc编译c math.c时sin cos等未定义

这个时候一般没有引用到本地lib库,所以go build的时候需要加入静态编译库

流程如下:

wget https://musl.libc.org/releases/musl-1.2.4.tar.gz

tar -zxvf musl-1.2.4.tar.gz && cd musl-1.2.4/

./configure

make && make install

cp /usr/local/musl/bin/musl-gcc   /usr/local/bin

go编译时启动cgo静态编译
CGO_ENABLED=1 GOOS=linux GOARCH=amd64 CC=musl-gcc CGO_LDFLAGS="-static" go build -o ../bin/mypro mypro

 

如果你是用docker镜像方式构建可以使用如下dockerfile文件

FROM golang:1.14.4-alpine
ENV TZ=Asia/Shanghai
RUN echo -e http://mirrors.aliyun.com/alpine/v3.10/main/ > /etc/apk/repositories \
    && apk update \
    && apk add --no-cache tzdata gcc g++ libffi-dev musl-dev openssl-dev make linux-headers libc-dev libc6-compat binutils \
    && ln -sf /usr/share/zoneinfo/$TZ /etc/localtime \
    && echo $TZ > /etc/timezone

USER root
WORKDIR /workspace
COPY code /workspace/code
RUN cd/workspace/code\ 
&& GOPROXY="https://goproxy.cn,direct" GO111MODULE="" GOMOD="on" GOARCH=amd64 CGO_ENABLED=1 GOOS=linux go build mypro

 

备注:  linux centos 使用 alpine 编译的二进制文件 报错 /lib/ld-musl-x86_64.so.1: bad ELF interpreter 解决方法

curl https://forensics.cert.org/cert-forensics-tools-release-el7.rpm -o cert-forensics-tools-release-el7.rpm 
rpm -Uvh cert-forensics-tools-release*rpm
yum --enablerepo=forensics install -y musl-libc-static
posted @ 2023-05-12 15:59  ruanqin  阅读(331)  评论(0编辑  收藏  举报