C程序中函数名与宏名称同名


C语言中,函数名称和宏名称可以相同。可以参考下面的示例程序。
///////////////////////////////////////////test.cpp
#include <stdio.h>

void print(int value) {
    printf("%d\n", value);
}

#define print(x)  printf("hello");    \
                print(x)

int main() {
    print(23);

    return 0;
}
上面的程序在vc和gcc下都可以运行,输出结果是:hello23。
究其原因,我们知道编译器编译C语言程序时,先执行预编译,然后再执行编译、汇编和链接等步骤。预编译阶段质主要处理宏,而编译阶段同名的宏已经被替换掉了,故而此时是不存在标识符冲突的。
但是,函数名称和宏名称同名是有前提的,同名的宏定义必须在同名函数实体之下。再请参考下面示例程序。
/////////////////////////test.cpp
#include <stdio.h>


#define print(x)  printf("hello");    \
                print(x)

void print(int value) {
    printf("%d\n", value);
}

int main() {
    print(23);

    return 0;
}
这个程序是编译不过去的,因为宏定义在同名函数定义之前,预编译到print函数时,其名称也被当做宏进行处理,预编译完毕后,编译器编译是程序显然是不对的。如果程序的文件名称是test.c,则linux环境可以通过命令gcc -E test.c > test.i,可以看到预编译结果,有心者可以自己分析下,仔细看看print函数的预编译结果。
如果要定义一个与函数名同名的函数,我们须在函数定义之后再定义宏,似乎不太优雅,没有别的方法么?有的,多文件实现之。有多文件及其源码如下:
/////////////////////////print.h
#ifndef __PRINT_H__
#define __PRINT_H__

 


void print(int value);

 


#endif

 


/////////////////////////print.cpp
#include "print.h"
#include <stdio.h>

 


void print(int value) {
printf("%d\n", value);
}

 


/////////////////////////print_inf.h
#ifndef __PRINT_INF_H__
#define __PRINT_INF_H__

 


#include "print.h"

 


//print macro
#define print(x)printf("hello");\
print(x) //print function

 


#endif

 

 

 


/////////////////////////test.cpp
#include "print_inf.h"
#include <stdio.h>

int main() {
print(23);

 


return 0;
}
编译程序命令是gcc test.c print.c -o test,运行程序test,输出是hello23。

  • 1
  • 2
  • 下一页

相关内容