C程序找到当前文件名

Gom*_*thi 5 c file

我想用C程序显示我当前的C文件.我知道可执行文件的名称可以通过argv[0].但我想要文件名作为'hello.c'例子.可能吗?

Jon*_*art 15

单个程序可以包含多个 C文件.那你要找哪一个?

__FILE__宏被这个原因作出.它由预处理器替换,其中包含正在编译的当前源(.C)文件的名称.

main.c中

#include <stdio.h>
int main(int argc, char** argv)
{
    printf("Executable name: %s\n", argv[0]);

    printf("This is %s() from %s, line %d\n",
        __FUNCTION__, __FILE__, __LINE__);

    one();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

one.c

#include <stdio.h>
void one(void)
{
    printf("This is %s() from %s, line %d\n",
        __FUNCTION__, __FILE__, __LINE__);
}
Run Code Online (Sandbox Code Playgroud)

输出(假设可执行文件名为"hello.exe"):

Executable name: hello.exe
This is main() from main.c, line 4
This is one() from one.c, line 3
Run Code Online (Sandbox Code Playgroud)

也可以看看: