在C中,实现头文件的最低要求是什么?

时间:2012-02-27 15:26:01

标签: c header-files

我有一个头文件,如下所示:

typedef struct PriorityQueueStruct PriorityQueue;

/**
 * Type definition for an Element.
 */
typedef struct ElementStruct
{
    int element;
} Element;

/**
 * Type definition for a priority.
 */
typedef struct PriorityStruct
{
    int priority;
} Priority;

/**
 * Structure for containing the resultant values for a 
 *    call to 'createPriorityQueue'.
 *
 * 'token' is the identifier for the created data structure 
 *     and is to be used in any call to query or modify it.
 * 'resultCode' tells whether the function was successful or not in creating a 
 *     priority queue.  1 for success or an error code describing the failure.
 */
typedef struct InitializationResultStruct
{
        PriorityQueue* pq;
        int resultCode;
} InitializationResult;

/**
 * Structure for containing the resultant values for a 
 *    call to 'peek'.
 *
 * 'peekedValue' is the first-most value from the priority queue
 * 'resultCode' tells whether the function was successful or not in creating a 
 *     priority queue.  1 for success or an error code describing the failure.
 */
typedef struct PeekResultStruct
{
        Element element;
        Priority priority;
        int resultCode;
} PeekResult;

我对如何在我的简单类中实现此头文件感到有点迷失,这是一个优先级队列的应用程序(称为TriageQueue)。我是否单独将结构留在头文件中?我如何实现功能(感谢小费!)?我感谢任何帮助!

3 个答案:

答案 0 :(得分:2)

C没有类或方法。它有功能。

是的,假设你必须实现这个特定的接口,当然你需要单独留下声明。

虽然看起来有些破碎,但是注释引用了未出现在声明中的名称(tokenpeekedValue)。

答案 1 :(得分:2)

实现在.c,.cpp文件上。

关于是否包含其他定义,取决于您和您的设计。恕我直言,如果结构与类有关系,我会将它们放在与类相同的标题中。

答案 2 :(得分:1)

首先,我建议在头文件中放置一个“防护”,以防止基于重复定义的编译器错误消息问题(如果头文件中有任何内容)。您可以通过在头文件的顶部放置以下C-preprocessor指令来完成此操作:

#ifndef YOUR_HEADER_FILE_NAME_H
#define YOUR_HEADER_FILE_NAME_H

//...the contents of  your header file

#endif //<== Place this at the very end of the header.

接下来,在.c文件中,为简单起见,将头文件放在与.c文件相同的目录中,然后在.c文件的顶部写入C预处理器指令#include "MyCodeFile.h"。您还需要包含C标准库中您正在使用printfmalloc等函数的任何其他标头。由于标准库中的这些标头不在与.c文件相同的目录,您需要使用带有这些标题的尖括号,它指示编译器在开发环境中定义的一组搜索目录中查找文件(大多数此类内容应该已经为您设置,因为它们位于/usr/include等标准位置。例如,#include <stdio.h>将包含C标准库中的I / O功能。

最后,在你的.c文件中,一旦你包含了头文件,只需从声明创建你的函数的定义等等。在头文件中创建。例如,如果头文件中包含以下内容:

void function(int a, int b);

然后在.c文件中,您实际上会创建定义,如:

void function(int a, int b) { ... }

对于像当前头包含的结构类型一样,“定义”将是该结构类型的实例的实际声明。这当然可以在函数内部发生,在堆栈上分配struct对象,或者可以静态分配为全局变量,或者可以使用{{struct对象动态分配内存。 1}}。

相关问题