Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ include .h includes .cpp with same name as well?

I have text.cpp which includes header.h and header.cpp which includes header.h.

Will header.cpp be compiled as well? I'm following a guide here, and I am thoroughly confused.

Also, what is the correct terminology for what I am asking? I know I sound like a moron, and I apologize, but I'm ignorant.

Oh, int main() is in test.cpp.

Also, if header.cpp includes <iostream>, why can't I use iostream function calls in text.cpp if it is included? If I include <iostream> in text.cpp will it be included in the program twice (in other words, bloat it)?

like image 813
aaron Avatar asked Apr 04 '10 04:04

aaron


1 Answers

You tell your compiler which C++ files to compile. #include has nothing to do with it.

For example, if you are using g++:

g++ text.cpp // Doesn't compile header.cpp
g++ text.cpp header.cpp // Compiles both

(or, alternatively you can compile one file at a time and then link them)
g++ text.cpp -o text.o
g++ header.cpp -o header.o
g++ text.o header.o -o your-program

If you use Visual Studio and you created a project, all C++ files you create will be automatically compiled.

If you are using neither, tell me the name of your compiler and I can tell you the exact syntax :)


Now, for your other question:

Also, if header.cpp includes iostream, why can't I use iostream function calls in text.cpp if it is included? If I include iostream in text.cpp will it be included in the program twice (in other words, bloat it)?

#include tells the compiler to simply "copy all the contents of the file you are including, and paste them where the #include line is". So, in theory, you could simply open iostream with notepad, select all, ctrl-c and ctrl-v it in your .cpp file and the end effect will be exactly the same =)

So yes it needs to be included for each .cpp file in which you wish to use it, and it won't "bloat" your program: it contains only class definitions, extern functions, etc.

Oh, and this goes without saying, but C++ is a very very vast and difficult programming language, you will have much better luck learning it through a book than a guide. If you don't want to spend any money, an okay free (downloadable) C++ book is Thinking in C++, Bruce Eckel. Otherwise if you want to buy one you can find a good list here.

like image 131
Thomas Bonini Avatar answered Sep 25 '22 15:09

Thomas Bonini