2

我刚刚开始使用 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” (这个有意义)
4

3 回答 3

3

包含的基础是确保您的标题只包含一次。这通常使用如下顺序执行:

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

/* Your code here ... */

#endif /* header_h_ */

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

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

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

A 对于您的特定问题,aStruct.h使用struct smallerStruct但对它一无所知,特别是它能够分配aStruct变量的大小。aStruct.h需要包括smallerStruct.h. 在编译时包含smallerStruct.hbefore aStruct.hinmain.c并不能解决问题aStruct.c

于 2010-02-19T14:27:13.503 回答
2

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

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

于 2010-02-19T21:21:14.050 回答
0

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

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

于 2010-02-19T14:45:56.027 回答