【问题标题】:How to get current source path in C++ - Linux如何在 C++ 中获取当前源路径 - Linux
【发布时间】:2013-12-05 07:42:33
【问题描述】:

我希望能够得到当前的源文件路径。

string txt_file = CURRENT_FILE_PATH +"../../txt_files/first.txt";
inFile.open(txt_file .c_str());

有没有办法获得 CURRENT_FILE_PATH ? 我不是指可执行路径。我的意思是运行代码的源文件的当前位置。

非常感谢, 乔拉。

【问题讨论】:

  • 您的要求似乎不清楚。当前工作目录由getcwd() 给出,源文件的路径可通过__FILE__ 宏访问。
  • 您对模块的询问意味着可执行文件,因此您需要工作目录,这就是答案stackoverflow.com/questions/143174/…
  • 也许这个词:模块不正确。我想要源文件的路径。 FILE 给了我相对路径。我想要完整的路径。
  • 对于 Windows,请参阅 this question,对于 Linux/OSX,请参阅 this question
  • 答案是使用 realpath() 函数。我已经尝试过了,但它需要一个相对路径才能开始。我没有。我对源文件位置“一无所知”。

标签: c++


【解决方案1】:

用于编译源文件的路径可通过标准 C 宏 __FILE__ 访问(参见 http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html

如果您将绝对路径作为编译器的输入(至少对于 gcc),__FILE__ 将保存文件的绝对路径,反之亦然。其他编译器可能略有不同。

如果您使用的是 GNU Make,并且您将源文件列在变量 SOURCE_FILES 中,如下所示:

SOURCE_FILES := src/file1.cpp src/file2.cpp ...

您可以确保文件由它们的绝对路径给出,如下所示:

SOURCE_FILES := $(abspath src/file1.cpp src/file2.cpp ...)

【讨论】:

    【解决方案2】:

    C++20 source_location::file_name

    除了__FILE__,我们现在还有另一种方法,无需使用旧的 C 预处理器:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1208r5.pdf

    文档只是说:

    constexpr const char* file_name() const noexcept;

    5 返回:当前源文件的假定名称 (14.2) 表示 通过这个对象作为 NTBS。

    其中 NTBS 表示“空终止字节字符串”。

    当支持到达 GCC 时我会尝试一下,带有g++-9 -std=c++2a 的 GCC 9.1.0 仍然不支持它。

    https://en.cppreference.com/w/cpp/utility/source_location 声明用法如下:

    #include <iostream>
    #include <string_view>
    #include <source_location>
    
    void log(std::string_view message,
             const std::source_location& location std::source_location::current()
    ) {
        std::cout << "info:"
                  << location.file_name() << ":"
                  << location.line() << ":"
                  << location.function_name() << " "
                  << message << '\n';
    }
    
    int main() {
        log("Hello world!");
    }
    

    可能的输出:

    info:main.cpp:16:main Hello world!
    

    【讨论】:

      猜你喜欢
      • 2018-05-30
      • 2019-02-18
      • 2020-11-21
      • 2016-06-04
      • 2018-03-11
      • 1970-01-01
      • 2014-03-10
      • 2014-07-19
      • 2010-10-12
      相关资源
      最近更新 更多