gpt4 book ai didi

c - 限制#include 只搜索当前目录

转载 作者:行者123 更新时间:2023-12-03 21:58:58 29 4
gpt4 key购买 nike

#include按照惯例,使用引号与尖括号来指示预处理器是否应该在系统头目录之前搜索当前目录。

假设您只想搜索当前目录,如果在那里找不到该文件,则会出现错误而停止。使用路径而不仅仅是文件名这样做是否有效?如

#include "./foo.h"

最佳答案

标准#include语法不支持您的要求。

但是,您可以通过两种方式解决此问题:

  • 如果你只需要包含当前目录下的文件,那么 GCC 标志 -nostdinc就足够了。它禁止标准包含路径,只留下当前目录。
    $ echo 'int func(void) {return 1;}' > foo.h
    $ echo '#include "foo.h"' | gcc -E - # success
    $ echo '#include "foo.h"' | gcc -nostdinc -E - # success
    $ echo '#include "stdio.h"' | gcc -E - # success
    $ echo '#include "stdio.h"' | gcc -nostdinc -E - # failure
  • 如果您还希望能够包含其他文件,您可以使用命令行定义来指定当前目录的绝对路径,并使用它的完整路径来包含严格位于当前目录中的文件。这仍然可以让您使用其他库的正常包含语法,并且也很容易集成到 Makefile 中。

    严格从当前目录导入的文件 ( foo.h ):
    int func(void) {return 1;}

    要在其中执行导入的文件 ( test.c ):
    #define XSTR(x) #x
    #define STR(x) XSTR(x)
    #define ABSOLUTE_PATH(lib) STR(CUR_DIR_PATH/lib)

    #include ABSOLUTE_PATH(foo.h)

    命令行:
    $ gcc -DCUR_DIR_PATH=$(pwd) -E test.c

    添加 #include ABSOLUTE_PATH(stdio.h)test.c将使上述失败按预期:
    $ echo '#include ABSOLUTE_PATH(stdio.h)' >> test.c
    $ gcc -DCUR_DIR_PATH=$(pwd) -E test.c
    test.c:7:33: fatal error: /home/marco/stdio.h: No such file or directory

    用 GCC 和 Clang 测试过,效果很好。
  • 关于c - 限制#include 只搜索当前目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60689285/

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