【发布时间】:2015-06-13 14:36:29
【问题描述】:
我正在尝试构建大型项目,其中我有以下头文件
错误.h
#ifndef __ERROR_H__
#define __ERROR_H__
#include <stdio.h>
#include <stdlib.h>
void error_validate_pointer(void *ptr)
{
if (ptr == NULL)
{
puts("Error with allocating memory");
exit(1);
}
}
#endif /* __ERROR_H__ */
我经常在我拥有的每个 .c 文件中使用这个函数(我在每个文件中都包含“error.h”),但我认为这个 #ifndef 可以保护我免受多重定义错误的影响。然而,在构建过程中,我收到以下错误:
../dictionary/libdictionary.a(state_list.c.o): In function `error_validate_pointer':
/home/pgolinski/Dokumenty/Programowanie/spellcheck-pg359186/src/dictionary/error.h:8: multiple definition of `error_validate_pointer'
../dictionary/libdictionary.a(hint.c.o):/home/pgolinski/Dokumenty/Programowanie/spellcheck-pg359186/src/dictionary/error.h:8: first defined here
../dictionary/libdictionary.a(state_set.c.o): In function `error_validate_pointer':
/home/pgolinski/Dokumenty/Programowanie/spellcheck-pg359186/src/dictionary/error.h:8: multiple definition of `error_validate_pointer'
../dictionary/libdictionary.a(hint.c.o):/home/pgolinski/Dokumenty/Programowanie/spellcheck-pg359186/src/dictionary/error.h:8: first defined here
我不断收到这些错误的原因可能是什么?如何避免?
【问题讨论】:
-
在每个文件中声明函数
static。这是一个链接器错误。您试图解决它的预处理器机制不起作用。编译器完全独立于其他所有源文件来处理每个源文件。换句话说,它每次开始处理源文件时都会“忘记”所有先前的定义。ifndef/define用于防止在在给定源文件上工作时“重复定义”,但不能超出它。在编译结束时,多个实例(全局函数或变量)被视为链接错误。 -
通常 .h 文件不包含实际代码。通常它们只包含声明和/或预处理器
#defines和宏。
标签: c