【Linux】编译C语言文件(-o -lpthread)

在gcc中使用-o编译

对于一个一般的程序,直接使用gcc <C语言文件名> -o <编译后生成的文件名>即可,例如以下程序:

// cpu.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc,int *argv[]){
    if(argc != 2){
        fprintf(stderr,"need parameter\n");
        exit(1);
    }

    char *str = argv[1];
    for(int i = 0;i < 4;i++){
        printf("%s\n",str);
        sleep(1);
    }
    return 0;
}

编译命令:gcc cpu.c -o cpu
在这里插入图片描述
(这个警告不重要)之后就会生成可执行文件cpu,我们可以使用./cpu运行它。

额外参数 -lpthread

对于含有<pthread.h>的程序,例如下面的:

// threads.c

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

volatile int counter = 0;
int loops;

void *worker(void *arg) {
    int i;
    for (i = 0; i < loops; i++) {
        counter++;
    }
    return NULL;
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "usage: threads <value>\n");
        exit(1);
    }
    loops = atoi(argv[1]);
    pthread_t p1, p2;
    printf("Initial value : %d\n", counter);

    pthread_create(&p1, NULL, worker, NULL);
    pthread_create(&p2, NULL, worker, NULL);
    pthread_join(p1, NULL);
    pthread_join(p2, NULL);
    printf("Final value : %d\n", counter);
    return 0;
}

在编译的时候需要加上额外的参数-lpthread,因为该头文件在Linux默认Import Library中没有,需要使用库libpthread.a进行编译链接。

命令gcc threads.c -o threads -lpthread

在这里插入图片描述
然后会生成可执行文件threads,使用./threads运行即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XV_

感谢您的认可,我会继续努力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值