Question

I have a function sortList() which uses mergeList(). And I declare them in the header file "sortList.h", and implement them respectively in sortList.cpp and mergeList.cpp. However when I compile, there is an error saying I didn't declare function mergeList() in the file "sortList.cpp". I wonder since I already declare mergeList() in the header file, shouldn't it be complied before implementation of sortList() (which uses mergeList)? Or shall I declare mergeList() again in sortList.cpp? Thanks!

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
Was it helpful?

Solution

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

In C, when header file is included (ie:#include "sortList.h"), it is as though the #include ... line is replaced with the entire code of the specified .h file is inserted at that point. In essence, the content of the .h file becomes part of the .c file (or, .cpp file) being compiled.

This is true for each .c file (or, .cpp file) which includes any specific .h file.

Hence, in the above question, "...shouldn't it be complied before implementation of sortList()", the answer is 'no'. Not 'before', but rather 'with'. Specifically, if prototypes sortList() and mergeList() exist in sortlist.h, for it is customary for both sortList.cpp and mergeList.cpp to #include "sortList.h"". Thus, the code of sortList.h becomes part of both these files.

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

No, just make sure that sortList.h is included in sortList.cpp.

OTHER TIPS

In order for your sortList function to use the mergeList function which is defined in a different source file, it will need to know that the function actually exists, and what it looks like. Adding

#include "sortList.h"

to "sortList.cpp" would be the easiest and most sensible way to do this.

Note that all cpp files are compiled to object files which than are linked. So treat every cpp file as its own module and supply the compiler with all information for that compile-target.

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

As already commented the easiest way to do this is to #include "sortlist.h" or to put function-prototypes on top of every cpp-file that uses the functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top