C 包含 .h 不工作?

标签 c gcc

我是 C 编程的新手。当我将 blank.h 文件包含到 Test.c 文件中时,程序将无法编译,但是当我将 blank.c 文件包含到 Test.c 文件中时,它可以正常编译。以下是所有 .c 和 .h 文件的源代码。我使用 gcc 作为我的编译器,我觉得我需要与它进行某种链接?任何帮助都会非常感谢!

这是Test.c源

#include <stdio.h>
#include "blank.h"
#include "boolean.h"

int main()  
{
    bool result = blank("");

    printf("%d\n", result);

    return 0;
}

这是blank.h的源码

// Header file for blank function

bool blank(char string[]);

这是blank.c源

#include "boolean.h"
#include "blank.h"
#include <regex.h>

bool blank(char string[])
{

    regex_t regex_blank;
    int blank = regcomp(&regex_blank, "[:blank:]", 0);

    blank = regexec(&regex_blank, string, 0, NULL, 0);

    if  ( string == NULL || blank == 1 )
        return true;
    else
        return false;
}

最后是 boolean.h

// Boolean

// Define true
#ifndef true
#define true 1
#endif

// Define false
#ifndef false
#define false 0
#endif

typedef int bool;

最佳答案

好的,所以我尝试了您提供的源代码。有几个问题。以下是我构建和修复内容的具体步骤。看看这是否适合您:

在一个文件夹中创建了 4 个文件:Test.c、blank.c、blank.h 和 boolean.h 复制代码。

从 shell 运行:

 gcc Test.c blank.c -o b

输出:

In file included from Test.c:2:0:
blank.h:3:1: error: unknown type name ‘bool’
blank.c: In function ‘blank’:
blank.c:11:46: error: ‘NULL’ undeclared (first use in this function)
blank.c:11:46: note: each undeclared identifier is reported only once for each function it appears in

修复第一个错误: 在 blank.h 中,在顶部添加了这个:#include "boolean.h"

修复第二个错误: 在 blank.c 中,在另一个包括之后添加了这个:#include <stdlib.h>

终端再次运行:

 gcc Test.c blank.c -o b

然后从终端运行 ./b 并打印 1。

关于C 包含 .h 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12666025/

相关文章:

c - 这个 for 语句有什么作用?

c - scanf() 迭代未知数量的整数

c - C中pid_t和int的区别

c - 链接静态库 C

c - 解决GCC警告: "dereferencing type-punned pointer will break strict-aliasing rules" by temporary pointer

c - 将 mex 文件链接到静态 mpfr 库时出现问题

c - 如何使用 getchar 和 putchar 忽略数字输入

c++ - 有没有可以将 Visual Studio 对象文件转换为 GCC 格式的工具?

c++ - 扩展 GCC 以进行内存管理

检查特定 gcc 编译器的 glibc 版本