【问题标题】:Compilation Failed when trying to access header files from other directory尝试从其他目录访问头文件时编译失败
【发布时间】:2021-03-05 03:40:33
【问题描述】:

下面是(示例)代码结构

/src    
 /poreA
     - a1.h
     - a1.cpp    
 /poreB
     - b1.h
     - b1.cpp    
 /poreC
     - c1.h
     - c1.cpp
     - c2.h    
 /maincpp
     -communicate.h
     -communicate.cpp
     -network.h
     -network.cpp
     -mainfile.cpp
     -mainfile.h

每个文件夹(poreA、poreB、poreC)都有自己的make文件

c1.h

 #include "a1.h"  

//  struct definitions are defined here

communicate.h

#include "../poreC/include/c1.h"

#ifndef POREC_H_

#define POREC_H_

network.h

#include "communicate.h"

ma​​infile.h

#include "network.h"

ma​​infile.cpp

#include "mainfile.h"

#include "network.h"

当我尝试编译时,

$ gcc -c mainfile.cpp

我得到错误

../../poreC/include/c1.h: fatal error: a1.h, no such file or directory
#include "a1.h"

我试图从类似的帖子中理解这个概念,但无法解决这个问题

How to invoke function from external .c file in C?

Including a header file from another directory

【问题讨论】:

  • 使用gcc -I../path/to/include/ 将新目录添加到包含搜索路径。您可以根据需要使用任意数量的-I

标签: c++ c


【解决方案1】:

当您在多个目录中有包含文件时,您可以使用 -I 标志告诉 gcc 到那里查看:

$ # if in ./src..
$ g++ -IporeA -IporeB -IporeC -Imaincpp maincpp/mainfile.cpp
$ # if in ./src/maincpp...
$ g++ -I../poreA -I../poreB -I../poreC mainfile.cpp

通常,小型项目可能有一个名为incinclude 的目录,所有标题都存放在其中。这样,gcc 将只需要一个 -Iinc 标志,而不是每个目录一个。

【讨论】:

  • 写得好,唯一的一点是单个/inc/include 路径很方便,大多数大型项目和库将指定许多单独的-I 位置。 (尤其是在使用pkg-config时)等等。
  • @DavidC.Rankin 感谢您的提醒,我编辑了答案以特别指出小项目。
  • 非常抱歉。这是我的类型错误。事实上,头文件 c1.h 调用的是 a1.h 而不是 c2.h。我编辑了帖子。我尝试了您提到的两种方法(来自 src 和来自 src/maincpp),它无法编译在 c1.h 中定义的 #include "a1.h" 错误是 ../poreC/include/c1.h :17:10: 致命错误: a1.h: No such file or directory #include "a1.h" ^~~~~~~~~~ 编译终止。
猜你喜欢
  • 1970-01-01
  • 2020-11-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
相关资源
最近更新 更多