设置
如果我有这样的程序
声明我的主库函数的头文件,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_H
至PRIMARY_HEADER_H
.正如@Jonathan Leffler 和@Pablo 所说,下划线名称是保留标识符
关于c - 如何在头文件中定义函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49099976/