gpt4 book ai didi

c++ - 如何在不使用 '..' 的情况下包含与当前源文件不在同一目录中的 C++ 头文件?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:25:48 26 4
gpt4 key购买 nike

例如:

project/utility/a.cpp

project/utility/a.h

是本项目中到处用到的一批函数的实现文件和头文件。

现在,想象一下

project/component/b.h

想要包含a.h。一个常见的解决方案是使用:

#include "../utility/a.h"

b.h 中。

但这在Google C++ style中是不允许的:

All of a project's header files should be listed as descendants of the project's source directory without use of UNIX directory shortcuts . (the current directory) or .. (the parent directory).

我尝试按照上面的文档所示将其包括在内,但它不起作用。

So what should I do to include it without using '.' or '..' ?

最佳答案

另见 What are the benefits of a relative path such as "../include/header.h" for a header?Should I use #include in headers?

您需要决定是仅使用头文件的基本名称(a.h 在您的问题的缩写示例中),还是使用子目录加上头文件名称 project/a.h )。只要 header 名称是唯一的,两者都可行;一般来说,子目录版本通常更好,需要的命令行选项更少。

你可以这样写:

#ifndef B_H_INCLUDED
#define B_H_INCLUDED

#include "utility/a.h"

…other material required…

#endif /* B_H_INCLUDED */

然后,在编译器命令行中包含一个选项:

-I ..

这确保编译器将找到 utility/a.h 作为 ../utility/a.h (除非某处存在名称冲突)。或者您可以指定项目的绝对路径:

-I /path/to/project

这将读取 /path/to/project/utility/a.h

关于c++ - 如何在不使用 '..' 的情况下包含与当前源文件不在同一目录中的 C++ 头文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30289915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com