linux平台交叉编译Windows 程序

xingyun86 2020-6-6 1064

linux平台交叉编译Windows 程序

第一步:安装mingw32 

本人 linux 环境是wsl ubuntu20.04  

sudo apt-get install mingw-w64

sudo apt-get install mingw-w64-tools 

sudo apt-get install mingw-w64-i686-dev 

sudo apt-get install mingw-w64-x86-64-dev 

上面这些可能会有安装出错的地方,检查网速或sudo apt-get update更新后再次尝试。安装完之后就可以编译代码了

第二步:编译测试

hello.c:

#include <stdio.h>
int main(int argc, char ** argv)
{
    printf("Hello World!\n");
}

$ i686-w64-mingw32-gcc -o hello.exe hello.c

第三步:编译pthread线程支持测试(发布到windows平台需要包含libwinpthread-1.dll才可运行)

test.c:

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
/* 声明结构体 */
struct member
{
    int num;
    char *name;
};
/* 定义线程pthread_routine */
static void * pthread_routine(void *arg)
{
    struct member *p;
    /* 线程pthread_routine开始运行 */
    printf("pthread_routine start!\n");
    /* 令主线程继续执行 */
    sleep(2);
    /* 打印传入参数 */
    p = (struct member *)arg;
    if(p)
    {
      printf("member->num:%d\n",p->num);
      printf("member->name:%s\n",p->name);
      
      free(p);
    }
    return NULL;
}
/* main函数 */
int main(int agrc,char ** argv)
{
    printf("enter %s\n", __func__);
    pthread_t tidp;
    struct member *p;
    /* 为结构体变量b赋值 */
    p = (struct member *)malloc(sizeof(struct member));
    p->num=1;
    p->name="ppshuai";
    /* 创建线程pthread */
    if ((pthread_create(&tidp, NULL, pthread_routine, (void*)p)) == -1)
    {
        printf("create error!\n");
        return 1;
    }
    /* 令线程pthread先运行 */
    sleep(1);
    /* 线程pthread睡眠2s,此时main可以先执行 */
    printf("main continue!\n");
    /* 等待线程pthread释放 */
    if (pthread_join(tidp, NULL))
    {
        printf("thread is not exit...\n");
        return -2;
    }
    return 0;
}

$ i686-w64-mingw32-gcc -o $1.exe $1.c -lpthread -D__WIN32

第四步:静态编译(只需将二进制文件发布到windows平台即可运行)

$ i686-w64-mingw32-gcc -static -static-libstdc++ -static-libgcc -o $1.exe $1.c -lpthread -D__WIN32

×
打赏作者
最新回复 (0)
只看楼主
全部楼主
返回