C/C++ full file path in assert macro

北慕城南 提交于 2019-12-13 16:05:28

问题


I am wondering if it's possible to display full file path using the assert macro? I cannot specify full file path in compilation command, is there still a way to do it?

My debug environment is linux/g++


回答1:


You can add the following macro option into your compilation line (Can be easily modify for your environment)

%.o: %.cpp
    $(CC) $(CFLAGS) -D__ABSFILE__='"$(realpath $<)"' -c $< -o $@

then you just have to this to have your full path:

#include <stdio.h>
int main()
{
  printf(__ABSFILE__);
  // will be expanded as: printf("/tmp/foo.c")
}

EDIT

Even better than this: The following rules is enough !!!

%.o: %.cpp
    $(CC) $(CFLAGS) -c $(realpath $<) -o $@

And you can now use __FILE__ macro:

#include <stdio.h>
int main()
{
  printf(__FILE__);
  // will be expanded as: printf("/tmp/foo.c")
}



回答2:


assert uses the __FILE__ macro to get the filename. It will expand to the path used during compilation. For example, using this program:

#include <stdio.h>
int main(void)
{
    printf("%s\n", __FILE__);
    return 0;
}

If I compile with 'gcc -o foo foo.c' and run, I'll get this output:

foo.c

But if I compile with 'gcc -o foo /tmp/foo.c' and run, I'll get this output instead:

/tmp/foo.c


来源:https://stackoverflow.com/questions/2449576/c-c-full-file-path-in-assert-macro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!