Newbie when it comes to c++, but have experience in other languages so giving it a go. I am having trouble understanding how to place functions in separate source files with headers.
Getting all sorts of errors when building this from mylib.h and mylib.cpp only. Using VS 2015.
1 2 3 4 5 6 7
Error C2086 'int mylib::time_t': redefinition mylib.cpp
Error C2447 '{': missing function header (old-style formal list?) mylib.cpp
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int mylib.cpp
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int mylib.h
Error C2143 syntax error: missing ';' before '{' mylib.cpp
Error C2146 syntax error: missing ';' before identifier 'getUTC' mylib.cpp
Error C2146 syntax error: missing ';' before identifier 'getUTC' mylib.h
Well, that solved all the errors, but I'm not following why it should be in the header and not the source file? Is it as simple as that is where the values being used are qualified? getUTC() returns a time_t so that is why the include was needed there... but say if the actual function on mylib.cpp uses another library like string it would be included in that file instead?
Is this format the recommended approach? I plan on separating aspects of the program into 'chunks' for easier editing/viewing later on when it becomes larger. This particular header/source would be common functions I use quite often, but another might be for file handling for example. I want to start off using the right approach and learn everything correctly.
I'm not following why it should be in the header and not the source file?
There are two solutions to your problem.
1) Move #include <ctime> to the header file as kbw suggested. That of course assumes, you put the include at the front of mylib.h. Had you put it at the end of mylib.h, you would have still gotten the same error.
2) Reverse the order of the includes in mylib.cpp, so that the #include <ctime> is before the #include "mylib.h"
Approach #1 is preferred on the style principle that your header file should be self contained. i.e. Any other headers that your header file requires are included locally. This eliminates the requirement that the user of your header file know what header files your header requires.
but say if the actual function on mylib.cpp uses another library like string it would be included in that file instead?
If mylib.cpp uses <string>, then it is perfectly fine to include the header for <string> within mylib.cpp.
If both mylib.h and mylib.cpp use <string>, there is no harm in including <string> in both places since all library files use include guards to prevent duplicate inclusion.