c++ - 库里面实现文件与头文件的问题

浏览:34日期:2023-04-12

问题描述

在github上看到一个项目,其中lib目录下的实现文件包含有另一个head文件夹下的头文件。lib文件夹和head文件夹不是同级的文件夹,head文件夹是另一个文件夹的子文件夹。但是lib文件夹里面的实现文件直接以#include 'head/xx.hpp'的方式包含着头文件的。想知道为什么可以这样包含,lib下的实现文件如何能够访问到那个头文件呢?先谢谢大家了

问题解答

回答1:

这时候就该用gcc里的-I参数,比如你的head/xxx.h位置在/path/to/libs/head/xxx.h,而饮用时用#include 'head/xxx.h',用以下参数编译即可:

gcc lib/xxx.c -I/path/to/libs

man gcc如下:

-I dir Add the directory dir to the list of directories to be searched for header files. Directories named by -I are searched before the standard system include directories. If the directory dir is a standard system include directory, the option is ignored to ensure that the default search order for system directories and the special treatment of system headers are not defeated . If dir begins with '=', then the '=' will be replaced by the sysroot prefix; see --sysroot and -isysroot.回答2:

应该是有个配置选项设置了前面省略的路径前缀。把项目clone下来,用sublime什么的全局搜索一下缺少的路径字符,就知道是在哪里配置的了。正常你写程序,前面的#include<stdio.h>这种也不是在当前可见目录下就放着的。linux系统有一些默认的环境变量类似C_INCLUDE_PATH这种,会存放一些系统路径,这些路径就是你include的时候会去默认搜索的头文件路径。你是可以继续往后面加入你自己的路径的。不知道你的项目是什么平台的,像Android这种,编译jni的时候,只要用LOCAL_C_INCLUDES指明头文件路径,代码里就可以省去很长的头文件路径了。你也可以搜索关键词linux系统 头文件搜索路径等等学习相关知识。

相关文章: