jmake 编译当前目录所有c/c++单文件

本文介绍了一个简单的C/C++编译脚本,能够自动识别并编译当前目录下的.c、.cc和.cpp文件。该脚本适用于单文件编译场景,不支持文件间的相互引用。

在一个目录下写一些单文件的c或者c++文件时,每次敲出命令如g++ a.cpp -o a感觉比较麻烦。

所以就模仿makefile的功能,实现了扫描当前目录,并将所有c文件、cc文件、cpp文件直接调用gcc/g++编译。

本程序的缺点之一就是不能用于文件间有相互include的情况,因为要扫描代码include了其他什么文件比较麻烦。而且不能在编译命令中加入其他库的选项。

 

使用方式:

1 jmake

 

源代码:

 1 /*
 2  * author: huanglianjing
 3  * 
 4  * this is a program to compile all single c/c++ file of current directory
 5  * 
 6  * usage: jmake
 7  */
 8 
 9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <dirent.h>
13 #include <string.h>
14 #include <sys/stat.h>
15 
16 int main()
17 {
18     struct dirent *entry;
19     struct stat statbuf;
20     
21     DIR *dp = opendir(".");
22     while ((entry=readdir(dp)) != NULL) {
23         lstat(entry->d_name,&statbuf);
24         if (!S_ISDIR(statbuf.st_mode)) {
25             char fname[57], ename[57], instruction[207];
26             strcpy(fname,entry->d_name);
27             strcpy(ename,entry->d_name);
28             int len = strlen(fname);
29             if (len>=3 && fname[len-1]=='c' && fname[len-2]=='.') {//.c
30                 ename[len-2] = '\0';
31                 sprintf(instruction,"gcc %s -o %s",fname,ename);
32                 printf("%s\n",instruction);
33                 system(instruction);
34             }
35             else if (len>=4 && fname[len-1]=='c'
36                     && fname[len-2]=='c' && fname[len-3]=='.') {//.cc
37                 ename[len-3] = '\0';
38                 sprintf(instruction,"g++ %s -o %s",fname,ename);
39                 printf("%s\n",instruction);
40                 system(instruction);
41             }
42             else if (len>=5 && fname[len-1]=='p' && fname[len-2]=='p'
43                     && fname[len-3]=='c' && fname[len-4]=='.') {//.cpp
44                 ename[len-4] = '\0';
45                 sprintf(instruction,"g++ %s -o %s",fname,ename);
46                 printf("%s\n",instruction);
47                 system(instruction);
48             }
49         }
50     }
51     closedir(dp);
52     return 0;
53 }

 

转载于:https://www.cnblogs.com/huanglianjing/p/4215170.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值