在C/C++文件中还原#line指令[重复]

2guxujil  于 8个月前  发布在  C/C++
关注(0)|答案(2)|浏览(109)

此问题已在此处有答案

Reset the C/C++ preprocessor #line the physical file/line(6个回答)
上个月关门了。
我正在尝试生成C/C++文件,其中我想覆盖特定代码区域中的行号和文件名。
考虑以下最小示例

#include <iostream>

int main() {
    #line 50 "inserted"
    std::cout << __LINE__ << " " << __FILE__ << std::endl;
    #line 6 "main.cpp"
    std::cout << __LINE__ << " " << __FILE__ << std::endl;
}

编译执行后将输出:

50 inserted
6 main.cpp

在上面的例子中,我使用#line指令覆盖了行和文件,这样它们在第一次打印时就有了一个自定义值。我现在想在第二次打印的“正确”的行和文件号,即。如果根本不使用#line指令,则会出现这些。
在上面的例子中,我通过硬编码正确的值来手动重置行和文件名。
有没有什么方法可以让预处理器自动恢复之前的#line指令,使其具有原始的行和文件名?

lf5gs5x2

lf5gs5x21#

我认为不可能重置#line指令。可能有一个先进的技巧来存储以前的状态,但我找不到它。
如果你有C++20的访问权限,那么source_location应该可以让你做你想做的事情。

goucqfw6

goucqfw62#

我想这是不可能的,原因类似于为什么BAR打印3和4,而不是3和3,在下面的例子中。

#include <iostream>

int main() {
    #define FOO 3   // say this is my __LINE__
    #define BAR FOO // which I try to remember
    std::cout << BAR << std::endl;
    #undef FOO     // with these two lines
    #define FOO 4  // I'm the preprocessor that increments __LINE__
    std::cout << BAR << std::endl; // but this sees the new value of __LINE__
}

因此,可能无法存储__LINE__的旧值。这样做似乎是一个运行时的事情...

相关问题