【问题标题】:g++ doesn't search for headers in current directory firstg++ 不会首先在当前目录中搜索标题
【发布时间】:2019-06-11 10:36:07
【问题描述】:

我在当前目录和目录inc 中有几个同名的标题a.h。我希望当前目录中的一个包含在main.cpp 中,但我需要目录inc 中的其他标题b.h。但是,GCC 不会首先在当前目录中搜索头文件。为什么?

main.cpp

#include <iostream>

#include "a.h"
#include "b.h"

int main(int argc, char *argv[])
{
    (void)argc;
    (void)argv;
    std::cout << FOO << std::endl;
    std::cout << BAR << std::endl;
    return 0;
}

build/a.h

#define FOO 1

inc/a.h


inc/b.h

#define BAR 1

来自build/ 目录:

build$ g++ -I. -I../inc ../main.cpp -o ../main
../main.cpp: In function ‘int main(int, char**)’:
../main.cpp:10:18: error: ‘FOO’ was not declared in this scope
     std::cout << FOO << std::endl;
                  ^

如果我删除 inc/a.h,一切正常。

gcc 版本 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.11)

【问题讨论】:

  • 最好明确地包含:#include &lt;A.h&gt; vs. #include &lt;inc/A.h&gt;
  • 什么意思?在main.cpp 中已经是#include "A.h",但GCC 包括inc/A.h,因为它先搜索inc,然后再搜索.
  • 我的意思是,删除所有-I 选项,只在源代码中包含特定文件。当您需要来自inc 的标题时,请执行#include &lt;inc/A.h&gt;。当您需要当前目录的标题时,请使用 #include &lt;A.h&gt;
  • 我会说它按预期工作。注意警告ignoring duplicate directory "." as it is a non-system directory that duplicates a system directory。当前目录(.)由 gcc 自动添加,因此被-I 标志忽略。然后,它首先检查用户包含路径,然后才是系统路径。作为一种解决方法,我会尝试-I../execDir 而不是-I.,但我不确定这是否会改变任何事情。

标签: c++ g++


【解决方案1】:

我设法通过添加来解决问题

export CPLUS_INCLUDE_PATH="/home"

我不知道为什么,但似乎 CPLUS_INCLUDE_PATH 以冒号开头会导致问题(因为我的 .bashrc 中有多个 export CPLUS_INCLUDE_PATH="$CPLUS_INCLUDE_PATH:path/to/include"

【讨论】:

    猜你喜欢
    • 2011-05-12
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    相关资源
    最近更新 更多