【原创】设置头文件路径, gcc -I 选项写法

网上关于gcc -I 的教程好少,试左成晚终于试左出来。

假如系目录 ~/testmake/下面有2个c文件同1个makefile: file1.c file2.c Makefile
系另个目录 ~/testmake/headfiles/ 有1个头文件: file2.h

其中file2.h内容为:
 
    

#ifndef __FILE2_H_
#define __FILE2_H_
       void File2Print();
#endif


即系头文件同埋c文件唔系同1个目录, 有两种写法:

===============================================================================================
第一种写法:
//file1.c
 
    

#include <stdio.h>
#include " ./headfiles/ file2.h"     //注明路径

int main(){
        printf("print file1$$$$$$\n");
        File2Print();
        return 0;
}


//file2.c
 
    

#include <stdio.h>
#include " ./headfiles/ file2.h"     //注明路径

void File2Print(){
        printf("Print file2**********\n");

}


//Makefile
 
   

helloworld: file1.o file2.o
gcc file1.o file2.o -o helloworld

file1.o: file1.c ./headfiles/file2.h
gcc -c file1.c -o file1.o

file2.o: file2.c ./headfiles/file2.h
gcc -c file2.c -o file2.o

clean:
rm *.o

呢种方法 没有使用gcc -I , 但系当file2.h的路径改变的话, 要同时维护makefile 和 file1.c file2.c 文件.



===============================================================================================
第二种写法:

//file1.c
 
     

#include <stdio.h>
#include " file2.h"     //<file2.h> 也可

int main(){
        printf("print file1$$$$$$\n");
        File2Print();
        return 0;
}


//file2.c
 
     

#include <stdio.h>
#include " file2.h"     // <file2.h> 也可

void File2Print(){
        printf("Print file2**********\n");

}


//Makefile
 
    

helloworld: file1.o file2.o
gcc file1.o file2.o -o helloworld

file1.o: file1.c //不需要指明依赖的file2.h 前提是file2.h这个文件存在于./headfiles/ ,而不能是其他名字.
gcc -c file1.c -I ./headfiles/ -o file1.o //加上-I 选项


file2.o: file2.c
gcc -c file2.c -I ./headfiles/ -o file2.o

clean:
rm *.o

呢种方法采用-I选项,  但只需维护makefile 1个文件。

转载于:https://www.cnblogs.com/nvd11/archive/2013/04/02/2996947.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值