首页 > 解决方案 > 如何使用预处理指令#define 定义新的头文件?

问题描述

尝试运行脚本时出现一些错误

 in file included from main.c:1:0:
 hello.h:1:2: error: invalid preprocessing directive #define__HELLO_H
 #define__HELLO_H
 ^~~~~~~~~~~~~~~~
 hello.h:5:2: error: #endif without #if 
 #endif 
 ^~~~~~~
 in file included from hello.c:2:0:
 hello.h:1:2: error: invalid preprocessing directive #define__HELLO_H
 #define__HELLO_H
 ^~~~~~~~~~~~~~~~
 hello.h:5:2: error: #endif without #if 
 #endif 
 ^~~~~~~

这是我的脚本

$ gcc main.c hello.c -o hello 
$ ./hello 

这是3个文件:

文件你好.h:

 #define __HELLO_H 

 void    hello(); 

 #endif 

文件你好.c:

 #include <stdio.h> 
 #include "hello.h" 

 void hello() 
 {      printf("Hello, I am tod,\n");         printf("Welcome to IT007!\n"); 
 } 

文件 main.c

 #include "hello.h" 

 int main() 
 { 
        hello();    return 0; 
 } 

我是初学者,你的帮助对我来说意义重大,谢谢

标签: clinux

解决方案


您必须按如下方式修复预处理器的使用:

  • #define在其操作数之间包含一个空格。
  • 要正确实施包含防护,您需要#ifndef#define.
  • 正如 wildplasser 所说,您不能使用以下划线开头的宏名称,因此请删除它们,或用您自己的其他前缀替换它们。
#ifndef HELLO_H
#define HELLO_H 

void    hello(); 

#endif // HELLO_H

推荐阅读