Post

去掉宏__FILE__的路径

本文介绍如何去掉宏__FILE__的路径,只显示文件名。

宏__FILE__展开后会带有路径信息,比如下面的代码:

1
2
3
4
5
6
7
8
#include<stdio.h>
#include<stdlib.h>

int main()
{
	printf("file_name:%s\n", __FILE__);
	return 0;
}

如果Makefile内容如下:

1
2
3
4
CFALG = -Wall

all: /home/helloworld/test.c
	gcc $(CFALG) $< -o test

编译运行,程序输出为:

1
file_name:/home/helloworld/test.c

为了不让宏_FILE__带有路径信息,可以在Makefile中重定义宏__FILE_

1
2
3
4
5
CFALG = -Wall
CFALG += -U__FILE__ -D__FILE__='"$(subst $(dir $<),,$<)"'

all: /home/helloworld/test.c
	gcc $(CFALG) $< -o test

编译运行,程序输出为:

1
file_name:test.c

取消宏_FILE__会产生编译警告,如果不想产生警告,可以考虑新建一个宏, 比如__FILENAME_

This post is licensed under CC BY 4.0 by the author.