繁体   English   中英

在编译命令中包含头文件时出现编译错误

[英]Compilation error while including header file in compile command

我有两个文件main.cheader.c

main.c有一些宏STR ,我想根据文件中的一些#define有条件地定义它们的值。

案例一

当我在main.c文件中包含header.c时,程序运行正常,如下所示:

主文件

#include<stdio.h>

#define _flag_b
#include "header.c"

void main(){
    printf("%s", STR);
}

头文件

#ifndef _flag_a
#define STR "flag a is activated.\n" 
#endif

#ifndef _flag_b
#define STR "flag b is activated.\n" 
#endif

汇编

anupam@g3:~/Desktop/OS 2020/so$ gcc main.c
anupam@g3:~/Desktop/OS 2020/so$ ./a.out
flag a is activated.

案例2

但出于某种原因,我想在编译命令中包含header.c而不是在main.c 这为我创造了这个问题,如下所示:

主文件

#include<stdio.h>

#define _flag_b
// #include "header.c"

void main(){
    printf("%s", STR);
}

头文件

#ifndef _flag_a
#define STR "flag a is activated.\n" 
#endif

#ifndef _flag_b
#define STR "flag b is activated.\n" 
#endif

汇编

anupam@g3:~/Desktop/OS 2020/so$ gcc main.c header.c
main.c: In function ‘main’:
main.c:7:15: error: ‘STR’ undeclared (first use in this function)
    7 |  printf("%s", STR);
      |               ^~~
main.c:7:15: note: each undeclared identifier is reported only once for each function it appears in
header.c:6: warning: "STR" redefined
    6 | #define STR "flag b is activated.\n"
      | 
header.c:2: note: this is the location of the previous definition
    2 | #define STR "flag a is activated.\n"
      | 

我对这个问题做了很多研究,并且能够理解为什么会出现这个问题。 但我无法解决这个问题。

请帮助我更好地理解这个问题,并为此提出一些解决方案。 也帮助我重新表述这个问题。

#define 为预处理器定义了一个宏 - 这意味着在编译之前,已定义宏的每个实例(在其定义之后)都被替换,在您的情况下,在 #define STR 之后......每个 STR 实例都被替换为指定的常量。 更多关于这里的

#include 只是复制一个文件并将其粘贴到指定的位置。 更多关于标题在这里

第一个示例有效,因为您包含了标头和代码,如下所示:

/*
  stuff included by stdio.h
*/
int main(void) {
  printf("%s", "flag a is activated.\n");
}

它可以轻松编译。 但是在第二个示例中,您尝试分别编译每个文件,因此第一个文件如下所示:

/*
  stuff included by stdio.h
*/
int main(void) {
  printf("%s", STR); //preprocessor doesn't recognise STR as a macro
}

第二个文件是空的。 所以现在编译器试图编译它,但它不知道 STR 是什么,所以你有一个错误。

如果要将其保留为 #define,则需要包含标题。

您可以在此处阅读有关预处理的更多信息。 如果要查看预处理器的输出,则需要使用 -E 标志,例如:gcc main.c -E -o mainPreprocessed.c

请下次将代码作为文本而不是图像包含 - 人们会更容易回答。

还有一件事:*.c 文件用于代码(您在 g++ 命令中添加),*.h 文件用于标头(您用 #include 包含)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM