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

标签 c one-definition-rule include-guards program-structure

设置

如果我有这样的程序

声明我的主库函数的头文件,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() 存在非法双重定义.什么是构造这个项目的源代码的正确方法,这样就不会发生双重定义?

最佳答案

你应该只在头文件中写你的函数原型(prototype),你的函数体应该写在一个 .c 文件中。
做这个 :
primary_header.h

/* 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_HPRIMARY_HEADER_H .正如@Jonathan Leffler 和@Pablo 所说,下划线名称是保留标识符

关于c - 如何在头文件中定义函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49099976/

相关文章:

c++ - 我可以用静态的、constexpr、类内初始化的数据成员做什么?

c++ - 在 header 中使用未命名的 namespace 会如何导致 ODR 违规?

c++ - 链接静态库和动态库时违反 ODR

c - 为什么我的文件执行此 header 两次,即使在 C 中 fork 时有保护措施?

c - 用户空间虚拟内存地址范围

c - STM32F103 Timer2不中断

c++ - 什么是正确的 LLVM header guard 样式?

linux - 抑制 gcc 警告 : "warning: this is the location of the previous definition"

c - C中的信号量和fork()

c - 关于释放 C 中的内存分配