Sch*_*ern 2 c linker struct header
这是一个更大的项目的缩减示例.你可以在这里看到它.
我有一个包含系统时间函数限制的头文件.称之为time_config.h.
#ifndef TIME_CONFIG_H
#define TIME_CONFIG_H
#define HAS_TIMEGM
#define SYSTEM_LOCALTIME_MAX 2147483647
#define SYSTEM_LOCALTIME_MIN -2147483648
#define SYSTEM_GMTIME_MAX 2147483647
#define SYSTEM_GMTIME_MIN -2147483648
const struct tm SYSTEM_MKTIME_MAX = { 7, 14, 19, 18, 0, 138, 0, 0, 0, 0, 0 };
const struct tm SYSTEM_MKTIME_MIN = { 52, 45, 12, 13, 11, 1, 0, 0, 0, 0, 0 };
#endif
Run Code Online (Sandbox Code Playgroud)
然后是一个定义我的时间函数的头文件.叫它mytime.h.它包括time_config.h.
#ifndef MYTIME_H
#define MYTIME_H
#include "time_config.h"
#ifndef HAS_TIMEGM
time_t timegm(const struct tm*);
#endif
#endif
Run Code Online (Sandbox Code Playgroud)
有mytime.c,包括mytime.h,并在必要时定义timegm().
我把它编译成目标文件......
gcc <a lot of warning flags> -I. -c -o mytime.o mytime.c
Run Code Online (Sandbox Code Playgroud)
并将其链接到测试二进制文件中,t/year_limit.tc还包括mytime.h.
gcc <a lot of warning flags> -I. mytime.o t/year_limit.t.c -o t/year_limit.t
Run Code Online (Sandbox Code Playgroud)
出了哪些错误:
ld: duplicate symbol _SYSTEM_MKTIME_MAX in /var/folders/eJ/eJzTVP7oG7GVsKYHJtMprE+++TI/-Tmp-//ccMe5DXb.o and mytime.o
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
由于time_config.h是在构建过程中由系统探测器生成的,因此将所有值保存在一个头文件中,甚至多个头文件中都非常方便.在构建过程中更改.c文件更加困难.
没有结构,它工作正常.如何在不导致此冲突的情况下在头文件中声明最小/最大日期结构?或者我编译和链接错误?
PS这是ANSI C89.
在标题(.h)中,您需要:
extern const struct tm SYSTEM_MKTIME_MAX;
extern const struct tm SYSTEM_MKTIME_MIN;
Run Code Online (Sandbox Code Playgroud)
在您的实现(.c)中,您需要:
const struct tm SYSTEM_MKTIME_MAX = { 7, 14, 19, 18, 0, 138, 0, 0, 0, 0, 0 };
const struct tm SYSTEM_MKTIME_MIN = { 52, 45, 12, 13, 11, 1, 0, 0, 0, 0, 0 };
Run Code Online (Sandbox Code Playgroud)