RBF*_*F06 2 c program-structure include-guards one-definition-rule
如果我有这样的程序
一个声明我的主库函数的头文件,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 */
Run Code Online (Sandbox Code Playgroud)
定义它的主要函数的实现文件。
/* 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();
}
Run Code Online (Sandbox Code Playgroud)
main()通过调用测试代码的文件primary()
/* main.c */
#include "primary_header.h"
int main()
{
/* just call the primary function */
primary();
}
Run Code Online (Sandbox Code Playgroud)
使用
gcc main.c primary_impl.c
Run Code Online (Sandbox Code Playgroud)
不链接,因为primary_header.h文件被包含两次,因此函数的双重定义是非法的helper()。为该项目构建源代码以防止双重定义的正确方法是什么?
你应该只在头文件中写你的函数原型,你的函数体应该写在一个 .c 文件中。
做这个 :
主要_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 */
Run Code Online (Sandbox Code Playgroud)
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");
}
Run Code Online (Sandbox Code Playgroud)
编辑:更改_PRIMARY_HEADER_H为PRIMARY_HEADER_H. 正如@Jonathan Leffler 和@Pablo 所说,下划线名称是保留标识符
| 归档时间: |
|
| 查看次数: |
4252 次 |
| 最近记录: |