如何在头文件中定义函数?

问题描述 投票:2回答:2

设置

如果我有这样的程序

一个头文件,声明我的主库函数primary()并定义了一个简短的简单辅助函数helper()

/* primary_header.h */
#ifndef _PRIMARY_HEADER_H
#define _PRIMARY_HEADER_H

#include <stdio.h>

/* Forward declare the primary workhorse function */
void primary();

/* Also define a helper function */
void helper()
{
    printf("I'm a helper function and I helped!\n");
}
#endif /* _PRIMARY_HEADER_H */

我的主要功能的实现文件,用于定义它。

/* primary_impl.c */
#include "primary_header.h"
#include <stdio.h>

/* Define the primary workhorse function */
void primary()
{
    /* do the main work */
    printf("I'm the primary function, I'm doin' work.\n");

    /* also get some help from the helper function */
    helper();
}

一个main()文件,通过调用primary()来测试代码

/* main.c */
#include "primary_header.h"

int main()
{
    /* just call the primary function */
    primary();
}

问题

运用

gcc main.c primary_impl.c

没有链接,因为primary_header.h文件被包含两次,因此有一个非法的双重定义函数helper()。构建此项目的源代码的正确方法是什么,以便不会发生双重定义?

c one-definition-rule include-guards program-structure
2个回答
4
投票

您应该只在头文件中编写函数的原型,函数体应该写在.c文件中。

做这个 :

primary_header.c

/* primary_header.h */
#ifndef PRIMARY_HEADER_H
#define PRIMARY_HEADER_H

#include <stdio.h>

/* Forward declare the primary workhorse function */
void primary(void);

/* Also define a helper function */
void helper(void);

#endif /* PRIMARY_HEADER_H */

primary_impl.c

/* primary_impl.c */
#include "primary_header.h"
#include <stdio.h>

/* Define the primary workhorse function */
void primary()
{
    /* do the main work */
    printf("I'm the primary function, I'm doin' work.\n");

    /* also get some help from the helper function */
    helper();
}

void helper()
{
    printf("I'm a helper function and I helped!\n");
}

编辑:将_PRIMARY_HEADER_H更改为PRIMARY_HEADER_H。正如@Jonathan Leffler和@Pablo所说,下划线名称是保留标识符


3
投票

您几乎从不在头文件中编写函数,除非将其标记为始终内联。相反,您在.c文件中编写函数并将函数的声明(非定义)复制到头文件中,以便可以在别处使用。

© www.soinside.com 2019 - 2024. All rights reserved.