我需要在编译时在代码中生成一系列序列号.我用这样的方式尝试了"__COUNTER__":
void test1()
{
printf("test1(): Counter = %d\n", __COUNTER__);
}
void test2()
{
printf("test2(): Counter = %d\n", __COUNTER__);
}
int main()
{
test1();
test2();
}
Run Code Online (Sandbox Code Playgroud)
结果如我所料完美:
test1(): Counter = 0
test2(): Counter = 1
Run Code Online (Sandbox Code Playgroud)
然后我在不同的.cpp文件中传播"__COUNTER__":
In Foo.cpp:
Foo::Foo()
{
printf("Foo::Foo() with counter = %d\n", __COUNTER__);
}
In Bar.cpp:
Bar::Bar()
{
printf("Bar::Bar() with counter = %d\n", __COUNTER__);
}
In Main.cpp:
int main()
{
Foo foo;
Bar bar;
}
Run Code Online (Sandbox Code Playgroud)
结果是:
Foo::Foo() with counter = 0
Bar::Bar() with counter = 0
Run Code Online (Sandbox Code Playgroud)
在我看来,"__ COUNTER__"作为 …