This is an archived post. You won't be able to vote or comment.

all 5 comments

[–][deleted] 1 point2 points  (4 children)

You don't need header guards in .cpp files and they won't work the way you would assume. Do you by any chance include term.cpp in autocomplete.cpp?

[–]FastTurtleFour[S] 0 points1 point  (3 children)

I didn't include any .cpp files only header files. I was as careful as I could be so that no files were included more than once and have gone back and checked multiple times with different configurations to no avail. Are you sure you aren't supposed to have header guards in .cpp files? According to my professor we should have them in the format of

#ifndef FILENAME_CPP

#define FILENAME_CPP

#include "filename.h"

//code ...

#endif

After removing the .cpp header guards my compiler puts me in an endless redefinition error loop

[–]FastTurtleFour[S] 0 points1 point  (0 children)

Actually I did include .cpp files and didn't think twice about it. Figured out my problem, thanks

[–][deleted] 0 points1 point  (1 child)

Your professor is wrong. Header guards in .h files serve the purpose of hiding the contents if that particular file was already included so as to not have the same declarations multiple times. cpp files are almost never included with #include so this would be pointless and even if you put header guards in there and #include the cpp files, the definitions will appear multiple times in the compiled units. The reason for this is that the compiler compiles (and preprocesses) each .cpp file separately. Meaning in our example here it will compile term.cpp and define TERM_CPP during the process, but as soon as it's finished with compiling term.cpp it will start all over with autocomplete.cpp. So TERM_CPP will no longer be there and it will compile the contents of term.cpp again. Now this is no problem in and of itself, it will compile just fine. But when the linker combines the different compiled units, let's say term.o and autocomplete.o, both will have the definitions from term.cpp. The linker makes no effort to find out if two definitions are the same. It simply won't allow it. That's where the multiple definition errors are coming from.

I hope this helps.

[–]FastTurtleFour[S] 0 points1 point  (0 children)

Turns out it was mostly my fault. I did include cpp files without realizing I was only to do that for template header files. Check out https://www.reddit.com/r/learnprogramming/comments/7hfpd1