“的多重定义”我有下面的“常量”标头:链接问题与编译错误
/* constants.h */
#ifdef __cplusplus
extern "C" {
#endif
#pragma once
#ifndef CONSTANTS_H
#define CONSTANTS_H
const char * kFoo = "foo";
const char * kBar = "bar";
#endif
#ifdef __cplusplus
}
#endif
我#include
-ing在文件X.c
和Y.c
这个头。
请注意,我是而不是包括这在X.h
或Y.h
。
将文件X.c
和Y.c
编译到目标文件中,该文件归档到名为libXY.a
的静态库中。
当我包括X.h
和Z.h
Y.h
,当我链接到libXY.a
,我不能没有错误编译Z.c
:
/* Z.h */
#include "X.h"
#include "Y.h"
我在尝试编译Z.c
当以下编译错误:
/path/to/libXY.a(X.o):(.data+0x0): multiple definition of `kFoo`
/path/to/libXY.a(Y.o):(.data+0x0): first defined here
/path/to/libXY.a(X.o):(.data+0x8): multiple definition of `kBar`
/path/to/libXY.a(Y.o):(.data+0x8): first defined here
我已经尝试设置kFoo
和kBar
到extern
,但这没有帮助。
我将如何解决多个定义,当我只有(通过头文件保护#ifndef CONSTANTS_H
),包括一旦常数?
也许不是眼前的问题(不知道),但你应该删除伪造'#pragma once',并在你的头文件中放置适当的多重包含守卫。标准格式为'#ifndef MYHEADER_H #define MYHEADER_H ....#endif' – 2012-01-28 23:08:43