在头文件中声明多个函数
multiple function declare in head file
我有一个使用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文件之上。
- Visual Studio中的函数声明和函数定义问题
- 为什么函数声明中允许 const?
- 如果 x.h 仅由函数声明组成,为什么有必要在 x 中包含 x.h.cpp
- * 和 ** 在 C++ 函数声明中是什么意思?
- 构造函数/函数声明参数列表中的统一初始化
- 在将函数声明为友元时,尖括号的含义是什么?
- 为什么转换函数声明不需要至少一个定义类型说明符
- 如何正确编写指针函数声明?
- 在"template"和函数声明之间使用:template<typename trait> using tr = base_trait<trait> void fn(tr::t
- 为什么要将函数声明和定义放在单独的文件中
- 为什么系统日志有两个不同的函数声明?
- 我如何获取数组的大小,以便我可以从函数声明所述数组
- 使用 enable_if 在按值传递与按引用传递之间更改函数声明
- JavaScript 中的一等函数和 C++ 中的函数声明
- C++ 通过函数声明后初始化向量
- VS2017 #error: : snprintf 的宏定义与标准库函数声明冲突
- C++ 17 个友元函数声明和内联命名空间
- MSVC 2017 - 错误 - 如何将模板类 X 的模板成员函数声明为嵌套类 X::Y 的好友
- 将派生类的构造函数声明为父类的友元
- 用于从 ANSI 字符串转换为 std::basic_string <TCHAR>的正确函数声明