将头文件链接到C++中的实现文件

Linking header files to an implementation file in C++

本文关键字:文件 C++ 实现 链接      更新时间:2023-10-16

我有一个关于在C++中链接文件的特殊问题。假设我有一个名为fmttime.h的头文件,我想将它链接到fmttime.cc(实现文件(,这就是我迄今为止所做的

 ExpandedTime* localTime(struct timeval* tv, ExpandedTime* etime);
 int main()
 {
     struct timeval tv;
     struct ExpandedTime etime;
     gettimeofday(&tv, NULL);
     localTime(&tv,&etime);
 }
 ExpandedTime* localTime(struct timeval* tv, ExpandedTime* etime)
 {
     tzset(); // Corrects timezone
     int epochT = (tv->tv_sec) - timezone; // Epoch seconds with
     int epochUT = tv->tv_usec;  // Timezone correction
     int seconds = epochT % 60;
     epochT /= 60;
     etime->et_sec = seconds;
     etime->et_usec = epochUT;
     int minutes = epochT % 60;
     epochT /= 60;
     etime->et_min = minutes;
     int hours = (epochT % 24) + daylight; // Hours with DST correction
     epochT /= 24;
     etime->et_hour = hours;
     printf("%d,%d,%dn", seconds, minutes, hours);
     printf("%dn", epochUT);
     printf("%dn", timezone);
     printf("%dn", daylight);
     return etime;
 }

所以基本上我已经在标题中包含了fmttime.h。我对整个过程有一些问题。在fmttime.h中,我只有这个函数原型(这是我实际需要的全部(。

 // Interface file for fmttime.h which is including the fmttime.c
 // Contains function prototype
 char* formatTime(struct timeval* tv, char* buf, size_t len);

现在,如果我想在fmttime.cc实现文件中使用这个函数,我需要重新声明函数原型吗?或者,它可以被跳过,因为头文件已经包含了它,因此包含在fmttime.cc中,因为通过#include链接了它。

所以我基本上想添加到。CC文件char*formatTime(struct-timeval*…..(,但不确定是否仍需要在中声明原型。CC或其在fmttime.h文件中处理。

#include对文件进行替换实际上是一种文本替换操作。标题的内容只是直接粘贴到包含它的文件中。

所以,你可以自己回答这个问题。想象一下,头文件中的代码实际上也在实现文件中(因为它是(。

头文件仅#包含在源文件中。它们没有链接。在处理了预处理器指令(如#include(后,编译器会将源代码编译到对象文件(.o(中。然后,将对象文件传递给链接器进行链接。

对于您的最后一个问题,我建议您尝试编译您的。不包含#include指令的CC文件,然后#include头文件并再次编译。

记住:

.h/hpp->函数原型、变量/结构/枚举定义

.c/.cpp->函数实现(.c/.cpp需要包含其相应的头(