在头文件中声明多个函数

multiple function declare in head file

本文关键字:函数 声明 文件      更新时间:2023-10-16

我有一个使用mergeList()的函数sortList()。我在头文件"sortList.h"中声明了它们,并分别在sortList.cpp和merglist .cpp中实现了它们。然而,当我编译时,有一个错误说我没有在文件"sortList.cpp"中声明函数mergeList()。我想知道,因为我已经在头文件中声明了mergeList(),不应该在sortList()(使用mergeList)实现之前进行编译吗?还是在sortList.cpp中重新申报mergeList() ?谢谢!

sortList.h:

#ifndef SORTLIST_H_INCLUDED
#define SORTLIST_H_INCLUDED
struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
  };
ListNode *mergeList(ListNode *left, ListNode *right);
ListNode *sortList(ListNode *head);
#endif // SORTLIST_H_INCLUDED

Q:I wonder since I already declare mergeList() in the header file, shouldn't it be complied before implementation of sortList() (which uses mergeList)?

在C语言中,当包含头文件(即:#include "sortList.h")时,就好像#include ...行被替换为在该点插入指定.h文件的整个代码。实际上,.h文件的内容成为正在编译的.c文件(或.cpp文件)的一部分。

对于包含任何特定.h文件的每个.c文件(或.cpp文件)都是如此。

因此,在上面的问题"...shouldn't it be complied before implementation of sortList()"中,答案是'否'。不是"before",而是"with"。具体地说,如果原型sortList()mergeList()存在于sortlist.h中,因为sortList.cpp和mergeList.cpp都是习惯的#include "sortList.h""。因此,sortList.h的代码成为这两个文件的一部分。

Q:Or shall I declare mergeList() again in sortList.cpp?

不,只要确保sortList.h包含在sortList.cpp.

为了让您的sortList函数使用在另一个源文件中定义的mergeList函数,它需要知道该函数实际存在,以及它看起来是什么样子。添加

#include "sortList.h"

到"sortList.cpp"是最简单和最明智的方法。

请注意,所有cpp文件都被编译为对象文件,而不是链接。因此,将每个cpp文件视为自己的模块,并向编译器提供该编译目标的所有信息。

见:http://www.cprogramming.com/compilingandlinking.html

如前所述,最简单的方法是#include "sortlist.h"或将函数原型放在每个使用函数的cpp文件之上。