我有 3 个 .c 文件 main.c、fun1.c、fun2.c
char buff[50];//in fun1.c
char *arg; //in fun2.c
arg = strstr(buff, "001"); //in fun2.c
我想在 fun2.c 中打印 buff
但它给出错误 buff
undeclared,即使我在 fun1.h 中将其声明为 extern char buff [];
fun1.c和fun2.c中各有函数
最佳答案
很难说您的特定程序出了什么问题,但这里有一个示例,它将 2 个 .c
文件与一个 .h
文件链接起来。
1.头文件functions.h
:
#include <stdio.h>
extern void func();
我使用 extern
为另一个文件提供定义。
2. 现在,一个使用此头文件的 functions.c
文件:
#include "functions.h"
void func() {
printf("hello");
}
这需要#include
头文件,并使用函数void()
来打印消息。
3. 最后,一个将它们链接在一起的 main.c
文件:
#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
int main(void) {
func();
return 0;
}
它还需要 function.h
,因为它使用 func()
。然后您可以将代码编译为:
gcc -Wall -Wextra -g main.c functions.c -o main
您还可以查看 makefile,这会将这段长编译行缩短为简单的 make
。
关于c - 在C中的不同文件中使用char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42290365/