Linux下GCC编译C/C++程序两种手段

发布于 2020-12-28  330 次阅读


一、测试文件说明

root@ws-tkpjiq-0:~/linuxLearn/gccTes# ls *.c *.h
head.h  helloWorld.c  printString.c

共计两个.c文件和一个头文件(.h)。

helloWorld.c.c文件的代码如下:

#include "stdio.h"
#include "head.h"
int main(){
  printf("Hello World!\n");
  int a=3;
  for(int i=0;i<=10;i++){
  a=stringOutput(3*i);
  printf("%d \n",a); 
 }
}

printString.c的代码:

#include "head.h"
int stringOutput(int a){
 return a*100;
}

头文件head.h:int stringOutput(int a);

file

二、Shell脚本实现编译

gcc -c helloWorld.c -linclude -o he1.o
gcc -c printString.c -linclude  -o he2.o
gcc he1.o he2.o  -o he
./he

file

三、makefile文件实现编译

excute.erp:newh1.o newh2.o
        gcc newh1.o newh2.o -o excute.erp
newh2.o:printString.c ./head.h
        gcc -c printString.c -I./ -o newh2.o
newh1.o:helloWorld.c ./head.h
        gcc -c helloWorld.c -I./ -o newh1.o
clean:
        rm -rf *.o

file

四、稍进阶版makefile

OBJ=newh1.o newh2.o
excute.exe:(OBJ)
        gcc(OBJ) -o excute.exe
newh2.o:printString.c ./head.h
        gcc -c printString.c -I./ -o newh2.o
newh1.o:helloWorld.c ./head.h
        gcc -c helloWorld.c -I./ -o newh1.o
clean:
        rm -rf *.o

file

五、总结

file