to avoid losing the track of my code, I decided to make a little "library" (not a real library lib.a but a separate code section lib.cpp with its own header lib.h).
What I couldn't manage so far is how to compile these three files (main.cpp, lib.cpp, lib.h).
When I try to compile it like this: g++ main.cpp lib.cpp -o main.exe
... then I get a looot of errors like "string is not declared" or class my_file has no member ...."
All in all, the compiler can't find any declarations/includes... why?
Thank you guys! That works great, I simply forgot to use "namespace std::"...
What I do not really understand is why I have to include "lib.h" two times. If the compiler needs this information for main.cpp to know where he can find the declaration of class "my_file", then he should also know where he can find the constructor or am I wrong? How can compiler know where to find the constructor but not where to find declaration? I mean, he gets the information by including lib.cpp in command line "g++ main.cpp lib.cpp -o main.exe" but there he also gets information about "lib.h" in lib.cpp, so why do I have to include this library two times?
Each of the source files is compiled separately; when lib.cpp is being compiled the compiler has no idea about what is is main.cpp and vice versa. Therefore, you need to include the header with the class definition in each separately. This is identical to how you need to include the <string> header in both source files.
Ok but then, what would happen if I forget to add lib.cpp to the command line? Then g++ will compile main.cpp successfully? What would happen if I'd like to create a my_file object if constructor is missing? (I don't have the possibility to test it right now, I'm not at home...)
Yes, but linking will fail as it cannot find definitions for used functions. If you won't use any of the missing functions, executable will be created normally.
Yes, but linking will fail as it cannot find definitions for used functions. If you won't use any of the missing functions, executable will be created normally.
Ahh, well that sounds logical! Thanks.
Unfortunatelly, one other error occured while creating my "little compiler starter":
When I try to add include paths to the command like this: g++ main.cpp my.cpp -o main.exe -I D:\QT\5.3\mingw482_32\include\QtWidgets
.. then it works, BUT when I try to add any second path: g++ main.cpp my.cpp -o main.exe -I D:\QT\5.3\mingw482_32\include\QtWidgets D:\QT\5.3\mingw482_32\include\QtCore
then I get (always the same, doesn't matter which folder the second one is) this error:
D:\QT\Tools\mingw482_32\bin\..\lib\gcc\i686.....ld.exe: cannot find D:\QT\5.3\mingw482_32\include\QtCore: permission denied
collect2.exe: error ld returned 1 exit status
Where is the problem with my code? I was googleing for this about 2 hours, unfortunatelly with no results...
EDIT:
Sorry, found my mistake. Stupid, I forgot to type the "-I" for every path... SOLVED