我刚刚开始使用 C 进行模块化编程。我认为我在包含内容上做错了,因为我得到了很多 conflicting types for 'functionName'previous declaration of 'functionName' was here 错误。我确实放置了包含守卫。

您是否知道解释 C 模块化编程的清晰教程,尤其是包含内容如何工作?


更新:我试图隔离我的问题。根据要求,这是一些代码。

更新2:更新的代码如下。错误也已更新。

/*
 * main.c
 */
#include <stdio.h>
#include "aStruct.h"

int main() {
    aStruct asTest = createStruct();

    return 0;
}

/*
 * aStruct.h
 */
#ifndef ASTRUCT_H_
#define ASTRUCT_H_

struct aStruct {
    int value1;
    int value2;
    struct smallerStruct ssTest;
};
typedef struct aStruct aStruct;

aStruct createStruct();

#endif /* ASTRUCT_H_ */

/*
 * smallerStruct.h
 */
#ifndef SMALLERSTRUCT_H_
#define SMALLERSTRUCT_H_

struct smallerStruct {
    int value3;
};
typedef struct smallerStruct smallerStruct;

smallerStruct createSmallerStruct();

#endif /* SMALLERSTRUCT_H_ */

/*
 * aStruct.c
 */
#include <stdio.h>
#include "smallerStruct.h"
#include "aStruct.h"

aStruct createStruct() {
    aStruct asOutput;

    printf("This makes sure that this code depends on stdio.h, just to make sure I know where the inclusion directive should go (main.c or aStruct.c).\n");

    asOutput.value1 = 5;
    asOutput.value2 = 5;
    asOutput.ssTest = createSmallerStruct();

    return asOutput;
}

/*
 * smallerStruct.c
 */
#include <stdio.h>
#include "smallerStruct.h"

smallerStruct createSmallerStruct() {
    smallerStruct ssOutput;
    ssOutput.value3 = 41;
    return ssOutput;
}

这会生成以下错误消息:

在aStruct.h:10

  • 字段“ssTest”的类型不完整

在 main.c:8

  • 未使用的变量“asTest” (这个有道理)
有帮助吗?

解决方案

多重定义问题很可能来自您包含代码的方式。您正在使用#include“aStruct.c”而不是#include“aStruct.h”。我怀疑除了 #include 之外,您还将 .c 文件编译到项目中。这会导致编译器由于同一函数的多个定义而变得混乱。

如果将 #include 更改为 #include "aStruct.h" 并确保三个源文件已编译并链接在一起,则错误应该消失。

其他提示

包含的基础是确保您的标头仅包含一次。这通常按如下顺序执行:

/* header.h */
#ifndef header_h_
#define header_h_

/* Your code here ... */

#endif /* header_h_ */

第二点是通过手动处理带有前缀的伪命名空间来处理可能的名称冲突。

然后只在标头中放入公共 API 的函数声明。这可能意味着添加类型定义和枚举。尽可能避免包含常量和变量声明:更喜欢访问器函数。

另一个规则是永远不要包含 .c 文件,只包含 .h。这就是模块化的要点:依赖于另一个模块的给定模块只需要知道它的接口,而不是它的实现。

A 对于您的具体问题, aStruct.h 用途 struct smallerStruct 但对此一无所知,特别是它的大小能够分配 aStruct 多变的。 aStruct.h 需要包括 smallerStruct.h. 。包括 smallerStruct.haStruct.hmain.c 编译时并没有解决问题 aStruct.c.

此类错误意味着函数声明(返回类型或参数计数/类型)与其他函数声明或函数定义不同。

previous declaration 消息将您指向冲突的声明。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top