【问题标题】:How to specify location of angle-bracket headers in gcc/g++?如何在 gcc/g++ 中指定尖括号标头的位置?
【发布时间】:2021-01-13 22:34:14
【问题描述】:

有没有办法告诉 gcc/g++/clang 在哪里寻找通过尖括号(“”)包含的标头?

我不对非系统文件使用尖括号约定,但问题是当我尝试使用我下载的某些包的标头时,所有包含的文件都会出错。

例如,假设我想包含来自我下载的名为 Foo 的模块的标头:

/foo-v1.0/include/DependencyA.hpp:

#ifndef DEP_A_HPP
#define DEP_A_HPP

class DependencyA
{
  ...
};

#endif

/foo-v1.0/include/Api.hpp:

#ifndef FOO_HPP
#define FOO_HPP
#include <Foo/DependencyA.hpp>

void doSomething(DependencyA* da);

#endif

然后,在我自己的代码中:

/mycode.cpp:

#include "/foo-v1.0/include/Api.hpp"

DependencyA* da = new DependencyA();
doSomething(da);

我得到一个编译错误: fatal error: 'Foo/DependencyA.hpp' file not found

我尝试过使用:

  • clang -c mycode.cpp -isystem./foo-v1.0/include -o mycode.o
  • clang -c mycode.cpp -isystem./foo-v1.0/include/ -o mycode.o
  • clang -c mycode.cpp -I./foo-v1.0/include -o mycode.o
  • clang -c mycode.cpp -I./foo-v1.0/include/ -o mycode.o

等等,无济于事。

如何告诉编译器将 &lt;Foo/**/*&gt; 解析为每个包含文件的特定根目录?

【问题讨论】:

  • 你有问题。实际文件路径均未以Foo/DependencyA.hpp 结尾
  • 您可能想要创建一个Foo 符号链接(可能在/usr/local/include,可能在您通过-isystem 添加的某个项目本地目录中)指向/foo-v1.0/include
  • 如果您选择man gcc,您将阅读gcc 命令的文档,其中包括您正在寻找的设置/选项。确实,出于上述原因,适当的gcc 设置/选项无论如何都不会帮助您;但是您应该知道man gcc 为所有可用的 gcc 选项提供了完整的文档。知道在哪里可以找到以及如何阅读技术文档是每个 C++ 开发人员的必备技能。

标签: c++ gcc clang


【解决方案1】:

答案已经在 cmets 中了。

要检查包含目录,可以使用此处描述的方法:What are the GCC default include directories?,最好将-替换为/dev/null

clang -xc -E  -v /dev/null

在我的机器上为clang 它提供了

ignoring nonexistent directory "/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/clang/11.0.0/include
 /usr/include
End of search list.

要了解如何操作此列表,只需阅读 gcc(或 clang)手册(man clang 或在 Internet 上找到它,例如 https://man7.org/linux/man-pages/man1/gcc.1.html)。对于 gcc,内容如下:

Options for Directory Search
       These options specify directories to search for header files, for
       libraries and for parts of the compiler:

       -I dir
       -iquote dir
       -isystem dir
       -idirafter dir
           Add the directory dir to the list of directories to be searched
           for header files during preprocessing.  If dir begins with = or
           $SYSROOT, then the = or $SYSROOT is replaced by the sysroot
           prefix; see --sysroot and -isysroot.

           Directories specified with -iquote apply only to the quote form
           of the directive, "#include "file"".  Directories specified with
           -I, -isystem, or -idirafter apply to lookup for both the
           "#include "file"" and "#include <file>" directives.

此描述之后是对头文件搜索顺序的详细描述,以及关于将哪个选项用于哪个目的的一些建议。你会在手册中找到它。搜索“目录搜索选项”。

你的代码中我真正不喜欢的是这一行:

#include "/foo-v1.0/include/Api.hpp"

它似乎包含标题的绝对路径,我从未见过这样的东西。我会把它改成

#include "Api.hpp"   

通过常用的编译器-I 命令行选项将/foo-v1.0/include 添加到搜索列表中。

【讨论】:

    猜你喜欢
    • 2022-10-17
    • 2012-12-20
    • 2013-08-04
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 2014-12-30
    相关资源
    最近更新 更多