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

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)?

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.

header.cpp is only compiled if you compile it. It doesn't get automagically sucked up when you compile test.cpp. To produce a running program, you also have to link the resulting .o files in a single binary, as follows (oversimplified):
c++ -c test.cpp
c++ -c header.cpp
c++ -o test test.o header.o

You compile each source file separately, or together, then link the resulting object modules.
E.g. Visual C++ (Together)
cl text.cpp header.cpp /Fefoo
or separately,
cl /c text.cpp
cl /c header.cpp
link text.obj header.obj /out:foo.exe
To get a resultant EXE image, foo.exe.
Also, if header.cpp includes
, 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)?
Since headers only contain declarations, there is no harm in including them many times. They will not bloat anything, since the compiler throws them away after doing type checking.
Though if you have type definitions in them, you need #include guards so that the types are not redefined.

Related

Can I include a cpp file in the main when there is a hpp?

For example:
I have a class called A. And there is:
A.hpp
A.cpp
main.cpp
for my project
By default, I only need to include A.hpp in the main so I can compile it, either using IDE such as Xcode or using:
g++ main.cpp A.cpp -o xxxxx
But the submission system only allows me to use:
g++ main.cpp -o xxxx
I tried to include A.cpp in the main, but the IDE says: main file cannot be included recursively when building a preamble
Is there any solution? I want to keep my hpp and cpp separately.
Can I include a cpp file
In theory, any file can be included.
But as a convention, you should never include cpp files.
But the submission system only allows me to use:
g++ main.cpp -o xxxx
If you cannot compile A.cpp then don't write such file at all. Write the definitions that you would have written in A.cpp into main.cpp instead. This achieves the same as including with a macro, but there won't be duplicate definitions in another cpp file.
You can #include any file you want. #include is automatic copy-paste. It looks in the file you tell it to include, and it reads whatever's in the file, and it pretends you wrote that in your original file. It doesn't care what's in the file, it just does that. You can include a .h file, a .hpp file, a .cpp file, a .txt file, a .py file, a .jpg file, or anything you want, as long as it's got valid C++ code in it.
Note that including a .cpp file is not the same as compiling it separately. And people expect that .cpp files are compiled separately, not included. To avoid confusing other programmers or the future version of yourself, you should rename the file to something else if you want to include it. You don't have to, but you should. If it's not a normal header file either (because you can't include it more than once), then you can make up some completely different extension, like .inc.

C++: Import/Include system

I'm writing a programming language, that convert the source files to C++ and compile they.
I want to add an way to work with a large number of files, compiling they to .o files, making it possible to use makefiles. A Better explanation (thank #Beta):
You have a tool that reads a source file (foo.FN) and writes C++ source and header files (foo.cpp and foo.h). Then a compiler (gcc) reads those source and header files (foo.cpp and foo.h) and writes an object file (foo.o). And maybe there are interdependencies (bar.cpp needs foo.h).
The problem is: my interpreter delete the .cpp and .h after the GCC compile they. Because this, it can't use #include, cause when it will compile, the referenced files don't exist anymore. How I can solve this?
There are two parts to the answer.
First, don't write explicit header files. You know what they should contain, just perform the #include operation yourself.
Secondly, don't write out the .cpp file either. Use gcc -x c++ - to read the code from standard input, and have your tool emit C++ to standard out, so you can run tool foo.FN | gcc -c -o foo.o -x c++ - to produce foo.o.

How does C++ linker know what .cpp files to use

I am a C++ learner and I came across a concept of separating code into multiple files to speed up compiling process on bigger projects.
However what the book doesn't tell me and I have tried to find it in other books and on the web, but with no luck is how does linker (during compilation) knows what files to include.
When I make new file I connect its header to the main file with #include "newfile.h", however in this header I don't write where to find definitions of functions.
So how I imagine the process is that it starts in the main file and there it finds "connections" to other files. The question is how it finds those .cpp files that as far as I see don't need to be named the same as its header file.
Exmple:
Main file:
#include <iostream>
#include "krneki_H.h"
using namespace std;
int main()
{
krneki1();
krneki2();
krneki3();
}
And header file:
void krneki1();
void krneki2();
void krneki3();
And new .cpp file:
#include <iostream>
#include "krneki_H.h"
using namespace std;
void krneki1() {
cout<<"Krneki1"<<endl;}
void krneki2() {
cout<<"Krneki2"<<endl;}
void krneki3() {
cout<<"Krneki3"<<endl;}
Notice that there is no indication to use second cpp file. It just knows to use it. Does it search all .cpp files in the map?
Thank you for answer.
You compile both .cpp files using gcc -c or a similar command line, and then pass both of the .o files produced to the linker. The linker does not magically figure out that you want to compile another .cpp file.
For example
gcc -c main.cpp -o main.o # compile
gcc -c krneki_H.cpp -o krneki_H.o # compile
gcc main.o krneki_H.o -o main # link
Your IDE may take care of these details automatically, in which case it compiles all .cpp files you added to your project, then links all the .o files produced by the compilation step.
No. It doesn't just know to use it. In your example, if you compile with main.cpp and without that new cpp file, you'll get an "undefined reference" error.
What happens is that you're using a fancy IDE that automatically compiles all cpp files. It includes them all by default in your makefile.
I recommend that you try to design a makefile from scratch, and see for yourself how you'll get that "undefined reference" error if you don't include the cpp file that has the implementations of your functions.

C++ Header and CPP includes

quick question.
I am trying to get C++ nailed down, and today I spent hours with a double definition linker error("this has already been defined!") and I finally realised it's because I had the layout as such:
main.cpp
#include Dog.cpp
Dog.cpp
#include Dog.h
Dog.h
// (Dog class and prototype of test function)
And now that I've cleared that up by including the Dog.h instead of the Dog.cpp in the main.cpp.
By including the .h file, does the .cpp file with the identical prefix get compiled with the program?
I was astounded when the program ran with only the .h included and no references whatsoever to Dog.cpp. I spent ages Googling but no answers really helped me understand what was going on.
Edit: I forgot to add that I prototyped in the .h, and defined the function for the class in the .cpp and that's what gave me the "already defined" error.
By including the .h file, does the .cpp file with the identical prefix get compiled with the program? I was astounded when the program ran with only the .h included and no references whatsoever to Dog.cpp.
No.
Your program is built in phases.
For the compilation phase, only declarations are needed in each translation unit (roughly equivalent to a single .cpp file with #includes resolved). The reason that declarations even exist in the first place is as a kind of "promise" that the full function definition will be found later.
g++ -c Dog.cpp # produces `Dog.o`
g++ -c main.cpp # produces `main.o`
For the linking phase, symbols are resolved between translation units. You must be linking together the result of compiling Dog.cpp and of compiling main.cpp (perhaps your IDE is doing this for you?), and this link process finds all the correct function definitions between them to produce the final executable.
g++ Dog.o main.o -o program # produces executable `program`
(Either that, or you actually haven't got to the link phase yet, and merely have an object file (Dog.o); you can't execute it, partially because it doesn't have all the function definitions in.)
The two phases can be done at the same time, with the "shorthand":
g++ Dog.cpp main.cpp -o program # compiles, links and produces executable
No, the .cpp file does NOT automatically get compiled. You can either do that manually, create a makefile, or use an IDE that has both of them in the same project.
You don't specify how you are compiling it. If you are using an IDE and have a new .h and .cpp to the project automatically then it will all be compiled and linked automatically.
There are 2 stages to making an executable to run: compiling and linking. Compiling is where the code gets interpretted and translated into lower level code. Linking is where all of the functions that you used get resolved. This is where you got the duplicate function error.
Inclusion does not automatically cause compilation, no.
In fact, the actual compiler never sees the #include statement at all. It's removed by an earlier step (called the preprocessor).
I'm not sure how it could build if you never compiled the Dog.cpp file. Did you reference any objects with code defined in that file?

Creating several precompiled header files using GNU make

I use gcc (running as g++) and GNU make.
I use gcc to precompile a header file precompiled.h, creating precompiled.h.gch; the following line in a Makefile does it:
# MYCCFLAGS is a list of command-line parameters, e.g. -g -O2 -DNDEBUG
precompiled.h.gch: precompiled.h
g++ $(MYCCFLAGS) -c $< -o $#
All was well until i had to run g++ with different command-line parameters.
In this case, even though precompiled.h.gch exists, it cannot be used, and the compilation will be much slower.
In the gcc documentation i have read that to handle this situation,
i have to make a directory called precompiled.h.gch and put
the precompiled header files there,
one file for each set of g++ command-line parameters.
So now i wonder how i should change my Makefile to tell g++ to create
the gch-files this way.
Maybe i can run g++ just to test whether it can use any existing file
in the precompiled.h.gch directory,
and if not, generate a new precompiled header with a unique file name.
Does gcc have support for doing such a test?
Maybe i can implement what i want in another way?
It seems weird to answer my own question; anyway, here goes.
To detect whether a suitable precompiled header file exists, i add a deliberate error to my header file:
// precompiled.h
#include <iostream>
#include <vector>
...
#error Precompiled header file not found
This works because if gcc finds a precompiled header, it will not read the .h file, and will not encounter the error.
To "compile" such a file, i remove the error first, placing the result in a temporary file:
grep -v '#error' precompiled.h > precompiled.h.h
g++ -c -x c++ $(MYCCFLAGS) precompiled.h.h -o MORE_HACKERY
Here MORE_HACKERY is not just a plain file name, but contains some code to make a file with unique name (mktemp). It was omitted for clarity.
There is a simpler way than introducing an #error in precompiled.h: never create this file at all. Neither G++ nor Visual C++ (at least up to 2005) expect the "real" file to be there, if a precompiled version is around (and if they get the necessary compilation flags).
Let's say the list of #includes that we want to precompile is called "to_be_precompiled.cpp". The filename extension doesn't matter much, but I don't like to call this a .h file, since it has to be used in a way different from genuine header files, and it's easier in Visual C++ if this is a .cpp. Then pick a different name to refer to it throughout the code, let's say "precompiled_stuff". Again, I I don't like to call this a .h file, because it's not a file at all, it's a name to refer to precompiled data.
Then in all other source files, the statement #include "precompiled_stuff" is not a genuine include, but simply loads precompiled data. It's up to you to prepare the precompiled data.
For g++, you need a build rule to create "precompiled_stuff.gch" from a source file whose name doesn't matter to the compiler (but would be "to_be_precompiled.cpp" here).
In Visual C++, the string "precompiled_stuff" equals the value of the /Yu flag and the precompiled data loaded comes from a .pch file with an unrelated name, that you also created from an unrelated source file (again "to_be_precompiled.cpp" here).
Only when building with a compiler without precompiled header support, a build rule needs to generate an actual file called "precompiled_stuff", preferably in the build directory away from the real source files. "precompiled_stuff" is either a copy of "to_be_precompiled.cpp", a hard or symbolic link, or a small file containing #include "to_be_precompiled.cpp".
In other words, you take the viewpoint that every compiler supports precompilation, but it's just a dumb copy for some compilers.