I just started learning C++ with Dev C++ as my IDE. One of the tutorials I'm using has a page in it about compiling a program made up of multiple files. It's simple stuff at this point, I have one file with a function in it, and the other file has all the other required code to call the function and output the results. The problem is that the tutorial doesn't tell me how to join these files so I can compile the program and have it work. There's seems to be multiple ways of doing this and I'd like them all but I'm mainly look for the simplest one right now.
I should also mention that I'm new at this so please try and keep your explanations simple and understandable.
In general, you would add both .cpp files to your project under the same target. It IDE will automatically add both files to the build and link them together.
That said, Dev-C++ is very, very old and unmaintained. It has not seen updates in several years. I strongly urge you to use a different IDE. There are many to choose from, including a fork of Dev-C++ called wxDev-C++. I'd actually recommend Code::Blocks or Visual Studio Express, which are both much more modern and have better support for debugging and many other features.
I am not sure of Dev-C++, but the concepts remain the same. So, here is how you can try to get both the files to work together
Each C++ file is a compilation unit - meaning, the compiler will convert one .cpp / .cxx file to one .obj / .o file (on Windows and Linux (or any Unix)) respectively
The obj files, called the object files contain the machine code (am skipping few internal details here) for the classes and functions present in that particular file
If you want to access the functions present in a different compilation unit, you need to link those two object files
Linking is a term that is used to, well, link two object files
There is a separate process (other than the compiler) which does the linking of the object files
So,in your case, you need to use the dev-c++ compiler and create separate object files
Then using the linker you link both the object files to create the final executable
If there are functions that exist in the .cpp files that you want to reference, you use the header files. The header files contain the function/class declarations. The .cpp files will have the implementations. So, in one of your .cpp file, (say) A.cpp, you include the header B.hpp and use the functions in the B.hpp file. The inclusion of headers will tell the compiler that the function declarations exist elsewhere and that the linker will take care of stringing all these references together to create the final executable.
Hope this helps, else, please don't hesitate to mention the files you are using and I can suggest how to link both the .cpp files together.
You must include the other files by using the #include preprocessor directive
in the top of the file where you have the main() function
For example:
#include "filename.h"
...
/* rest of code containing main function goes here */
...
#include "path/filename.c"
main
{
...
...
...
}
Related
This question was posted several times on StackOverflow, but most of the answers stated something similar to ".h files are supposed to contain declarations whereas .cpp files are supposed to contain their definitions/implementation". I've noticed that simply defining functions in .h files works just fine. What's the purpose of declaring functions in .h files but defining and implementing them in .cpp files? Does it really reduce compile time? What else?
Practically: the conventions around .h files are in place so that you can safely include that file in multiple other files in your project. Header files are designed to be shared, while code files are not.
Let's take your example of defining functions or variables. Suppose your header file contains the following line:
header.h:
int x = 10;
code.cpp:
#include "header.h"
Now, if you only have one code file and one header file this probably works just fine:
g++ code.cpp -o outputFile
However, if you have two code files this breaks:
header.h:
int x = 10;
code1.cpp:
#include "header.h"
code2.cpp:
#include "header.h"
And then:
g++ code1.cpp -c (produces code1.o)
g++ code2.cpp -c (produces code2.o)
g++ code1.o code2.o -o outputFile
This breaks, specifically at the linker step, because now you have two symbols in the same executable that have the same symbol, and the linker doesn't know what's it's supposed to do with that. When you include your header in code1 you get a symbol "x" and when you include your header in code2 you get another symbol "x". The linker doesn't know your intention here, so it throws an error:
code2.o:(.data+0x0): multiple definition of `x'
code1.o:(.data+0x0): first defined here
collect2: error: ld returned 1 exit status
Which again is just the linker saying that it can't resolve the fact that you now have two symbols with the same name in the same executable.
What's the REAL difference between .h and .cpp files?
They are both fundamentally just text files. From certain perspective, their only difference is the filename.
However, many programming related tools treat the files differently depending on their name. For example, some tools will detect programming language: .c is compiled as C language, .cpp is compiled as C++ and .h is not compiled at all.
For header files, the name does not matter at all to the compiler. The name could be .h or .header or anything else, it doesn't affect how the pre processor includes it. It is however good practice to conform to a common convention in order to avoid confusion.
I've noticed that simply defining functions in .h files works just fine.
Are the functions declared non-inline? Have you ever included the header file into more than one translation unit? If you answered yes to both, then your program has been ill formed. If you didn't, then that would explain why you didn't encounter any problems.
Does it really reduce compile time?
Yes. Dividing function definitions into smaller translation units can indeed reduce the time to compile said translation units compared to compiling larger translation units.
This is because doing less work takes less time. What is important to realise is that other translation units do not need to be recompiled when only one is modified. If you only have one translation unit, then you have to compile it i.e. the program in its entirety.
Multiple translation units are also better because they can be compiled in parallel, which allows taking advantage of modern multi core hardware.
What else?
Does there need to be anything else? Having to wait a few minutes to compile your program instead of a day improves development speed drastically.
There are some other advantages too regarding organisation of files. In particular, it is quite convenient to be able to define different implementations for same function for different target systems on order to be able to support multiple platforms. With header files, you must do tricks with macros while with source files, you simply choose which files to compile.
Another use case where implementing functions in header is not an option is distributing a library without source, as some middleware providers do. You must give the headers or else your functions cannot be called, but if all your source is in the headers, then you've given up your trade secrets. Compiled sources have to be at least reverse engineered.
Keep in mind that the C++ compiler is a fairly simple beast as far as file-handling goes. All it's allowed to do is a read in a single source-code file (and, via the pre-processor, logically insert into that incoming text-stream the contents of any files that the file #includes, recursively), parse the contents, and spit out the resulting .o file.
For small programs, keeping the entire codebase in a single .cpp file (or even a single .h file) works fine, because number of lines of code that the compiler needs to load into memory are small (relative to the computer's RAM).
But imagine you are working on a monster program, with tens of millions of lines of code -- yes, such things do exist. Loading that much code into RAM at once would likely stress the capabilities of all but the most powerful computers, leading to exceedingly long compile times or even outright failure.
And even worse than that, touching any of the code in a .h file requires the recompilation of any other files that #include that .h file, either directly or indirectly -- so if all your code is in .h files, then your compiler is likely to spend a lot of time unnecessarily recompiling a lot of code that didn't actually change.
To avoid those problems, C++ lets you place your code into multiple .cpp files. Since .cpp files are (at least traditionally) never #include'd by anything, the only time your Makefile or IDE will need to recompile any given .cpp file is after you've actually modified that exact file, or a .h file it #include's.
So when you've modified a function in the 375th .cpp file out of 700 .cpp files in your program, and now you want to test your modification, the compiler only has to recompile that one .cpp file and then re-link the .o files into an executable. If OTOH you've modified a .h file, compilation might be much longer, because now the build system will have to recompile every other file that includes that .h file, directly or indirectly, just in case you changed the meaning of something those files depend on.
.cpp files also make link-time issues much easier to deal with. For example, if you want to have a global variable, defining that global variable in a .cpp file (and maybe declaring an extern for it in a .h file) is straightforward; if OTOH you want to do that in a .h file, you'll have to be very careful or you'll end up with duplicate-symbol errors from your linker, and/or subtle violations of the One Definition Rule that will come back to bite you later on.
The REAL difference is that your programming environment lists .h and .cpp files separately. And/or populates file-browser-dialogs appropriately. And/or tries to compile .cpp files into object form (but doesn't do that to .h files). And whatever, depending on which IDE / environment you use.
The second difference is that people assume that your .h files are header files, and that your .cpp files are code source files.
If you don't care about people or development environments, you can put any damn thing you want in a .h or .cpp file, and call them any thing you want. You can put your declarations in a .cpp file and call it an "include file", and your definitions in a .pas file and call it a "source file".
I have to do this kind of thing when working in a constrained environment.
Header files weren't part of the original definition of c. The world got on perfectly well without them. Opening and closing lots of header files did slow down the compilation of c, which is why we got pre-compiled header files. Pre-compiled header files do speed up the compilation and linking of source code, but not any faster than just writing assembler, or machine code, or any other thing that didn't take advantage of the co-operation of other people or a design environment.
It is useful to put declarations in a header file, and definitions in a code source file. That's why you should do that. There isn't a requirement.
Whenever you see an #include <header.h> directive, pretend that the contents of header.h is being copied and pasted right where the #include directive appears.
.cpp files get compiled to become .obj files. They have no knowledge of the existence of any other .cpp file, and are compiled individually. That's why we need to declare things before we use them - otherwise the compiler won't know whether the function we're trying to invoke exists within a different .cpp file.
We use header files to share declarations amongst multiple .cpp files to avoid having to write the same code over and over for every single .cpp file.
I think I can do it in eclipse.
BTW, every time I make a new C++ file with the system default template.
It has #include <stdio.h> instead of #include <iostream>
How to fix it?
Why can't I put many separate source files with MAIN function in one project?
Because your linker can only allow a single implementation of a function per linking object, but you try to give him multiple int main implementations.
Because you did not configure XCode to behave differently, it tries to link all files into one binary object, leading to this conflict.
I think I can do it in eclipse.
Quite surely not, unless you forgot to add the source files to the list of files that end up in your binary, or you forget to define a binary that links everything together.
I always have problems with c++ on this, I spend more time trying to solve dependencies instead of programming when I setup a new project. I search the internet a way to do this automatic, or softwares that do that. In fact, I always program on geany and compile with shell script files...
So, is there a software to manage this? Do IDE's do that?
I always include .cpp files on my main.cpp and then I include the .hpp files on these .cpp. So, if I have a main.cpp, a object.hpp and a object.cpp, I will include the object.cpp in the main.cpp and the object.hpp on the object.cpp. Is there a better way to do that?
Can I just include the .hpp files and in the build script add every .cpp file?
I just cant find the answer on the internet, maybe im doing the wrong question...
I have found a nice article dealing with including files.
Common practice for all c++ header files is to simply define inclusion guards.
#ifndef TEST_H
#define TEST_H
// class definitions goes here
#endif
If there are some cyclic dependencies, consider forward declaration.
Every-time this header is included, the compiler checks, whether symbol TEST_H has been defined already. This basically guarantees, that contents of this file are included only once, and so that there is single declaration of the classes, defined in header file.
Good to know is, that directive "#include <>" does copy and paste all the contents of the included file.
Including .cpp file is not strictly disallowed, and sometimes good choice, it is considered a bad practice. As I mentioned, including file, means that all contents of the file are being duplicated at the place of inclusion. This is okay, for the header file with inclusion guard, but not okay for .cpp file, since every function definition inside this file, will be duplicated.
Not including file in the build script means, that only the those duplicated data are included in the build, otherwise you would end up with multiple function redefinition errors.
If you are looking for IDE, consider:
Visual Studio
Code Blocks
Eclipse
IDE won't do all the work, but you can be significantly more productive using good IDE.
TLDR:
Use inclusion guards
Include all .cpp files in build script.
Do not "#include" .cpp files.
In every .cpp file, include only needed headers, to reduce compilation time.
I see a lot of good suggestions with good practices but your mistake (including .cpp files from a .cpp file) suggest you're missing some concept in the C/C++ build process, I hope a little explanation would help you understand better and avoid the mistake.
Think of .c .cc .cxx .cpp files as modules, a .cpp file is a module, with your implementation of something, .h .hpp are just headers where usually you don't put implementations but declarations to be shared with multiple modules.
Usually each .cpp module is compiled to a binary object g++ -c -o mymod1.o mymod1.cpp then (once all modules are compiled) linked together g++ -o myprog mymod1.o mymod2.o ....
Even if you compile and link with a single command g++ -o myprog mymod1.cpp mymod2.cpp behind the scene g++ handle each module as single object.
I think is important you understand that each module/object know nothing about others, and if you need some other module (your main.cpp) to know something about mymod1.cpp a header file is required .h .hpp (mymod1.h) with the declarations needed to be shared: module global variables, defines, enums, function prototypes or class declarations, then just include mymod1.h in the module(s) where you want to use something of your mymod1 implementation (main.cpp).
Also, you write you're using a shell script to build, that's ok if your project are few files, better would be to use something like make, learn how to use it will require some time but then I bet geany have some facility to build projects based on Makefiles, make is the way to handle C/C++ projects from a long time.
I am starting some work using a third party library and when building it in Visual Studio 2010, I noticed I was receiving this linker warning many times (LNK4221). I looked at the sources used in creating the object files that were being linked and found that all of the implementation for these is located in the header files. Interestingly, I also noticed the project included corresponding .cpp files containing only a #include for the header with the implementation.
I am curious - what is the point of this and why would I want to use this technique? If the .cpp files aren't adding any value to the project, why shouldn't I just remove them to get rid of the linker warnings?
I tried searching for similar questions, but didn't find anything of interest. If you know of any, please link them.
Was the single #included file stdafx.h? I. That case, you're dealing with precompiled headers. The normal setup is for one .cpp file having "generate precompiled headers" compiler option, and the rest of the .cpp files in your project having "use pch".
I'm using this to make sure, that the header is at least in one file included at the first position. By doing so, I make sure that the header is compilable on it's own.
To convence the linker to not issue a warning, one could use an external variable with a very large variable:
int variable_with_a_name_that_includes_the_file_name_somehow = 42;
I just started a graphical C++ course and I have problem getting an overview how it is.
we got some starting code, two files; one of type "C++ Source" and another of "C/C++ Header".
its supposed to be a graphical program which fills the screen with color.
also, we are using some custom libraries such as SDL and GLM, in the same folder as those two files there is a folder named gml and loads of subfolders, which I wont get into.
I have downloaded mingw, cmake and Visual Studio 11 beta for c++.
I've tried making a normal Win32 program and also a forms-application for the graphical part, but its always something wrong when compiling.
My question: how are you supposed to handle C++ files? I just got used to java and there its so easy to just open the .java file and paste into your IDE, dealing with C++ makes me really confused.
Hmm... Where to begin...
Somethings that happen behind the scenes in other languages are much more visible in C++. The process of obtaining a binary (say, an executable) from C++ involves first compiling the source code (There are sub-steps of this but the compiler handles them) to obtain object files, then the object files are linked by the linker to generate a binary.
In theory, you could simply #include all the cpp files in a project, and compile them all together and "link" (although there's nothing to link) but that would take a very long time, and more importantly, in complex projects that could deplete the memory available to your compiler.
So, we split our projects into compilation units, and by convention a .cpp file represents a single compilation unit. A compilation unit is the part of your project that gets compiled to generate one object file. Even though compilation units are compiled separately, some code has to be common among them, so that the piece of code in each of them can use the functionalities implemented by the others. .h files conventionally serve this purpose. Things are basically declared (sort of announced) in them, so that each compilation unit knows what to expect when it's a part of a linking process to generate a binary.
There's also the issue with libraries. You can find mainly two kinds of things in libraries;
Already implemented functionality, shipped to you in the form of binary files including CPU instructions that can almost be run (but they've to be inserted in the right place). This form is accompanied by .h files to let your .cpp files know what to expect in the library.
The second type is functionality implemented directly in the .h
files. Yes, this is possible under special cases. There are cases,
where the implementation has to (a weak has to) accompany the
declaration (inlined functions, templated types etc.).
The first type comes in two flavors: A "static library" (.lib in windows, .a in linux), that enters your executable and becomes a part of it during linking, and a "dynamic library", that is exposed to your binary (so it knows about it) but that doesn't become a part of it. So, your executable will be looking for that dynamic library (.dll files in windows and .so files in linux f.x.) while it's run.
So, in order for your .cpp files to be able to receive services from libraries, they have to #include their .h files, to know about what there is in them. Later on, during linking, you have to show the linker where (what path in the file system) to find the binary components of those libraries. Finally, if the library is dynamic, the .dll's (or .so's etc.) must be accessible during run time (keep them in the same folder for instance).
While compiling your compilation units you have to tell the compiler where to find the .h files. Otherwise, all it will see will be #include <something.h> and it won't know where to find that file. with gcc, you tell the compiler with the -I option. Note that, you just tell the folder. Also of importance is that if the include directive looks like #include<somefolder/somefile.h> you shouldn't include somefolder in the path. So the invocation looks like:
g++ mycompilationunit.cpp -IPATH/TO/THE/INCLUDED/FILES -IPATH/TO/OTHER/INCLUDED/FILES -c
The -c option tells the compiler that it shouldn't attempt to make an executable just from this compilation unit, so it creates a .o file, to be linked with others later. Since we don't tell it the output file name, it spits out mycompilationunit.o.
Now we want to generate our binary (you probably want an executable, but you could also want to create a library of yours). So we have to tell the linker everything that goes into the binary. All the object files and all the static and dynamic libraries. So, we say: (Note g++ here also acts as the linker)
g++ objectfile1.o objectfile2.o objectfile3.o -LPATH/TO/LIBRARY/BINARIES -llibrary1 -llibrary2 -o myexecutable
Here, -L option is self explanatory in the example. -l option tells which binaries to look for. The linker will accept both static and dynamic libraries if it finds them on the path, and if it finds both, it'll choose one. Note that what goes after -l is not the full binary name. For instance in linux library names take the form liblibrary.so.0 but they're referred to as -llibrary in the linker command. finally -o tells the compiler what name to give to your executable. You need some other options to f.x. create a dynamic library, but you probably don't need to know about them now.
What is the difference between a .cpp file and a .h file?
Look at this answer. Also a quick google search explains a bit too.
Pretty much .h (header) files are declerations and .cpp (source) files are definitions. It is possible to combine both files into one .cpp file but as projects get bigger and bigger its becomes annoying and almost unreasonable.
Hope that helps.
In C++ there is a notion of a function declaration (the function signature) and a function definition (the actual code).
A header file (*.h) contains the declarations of functions and classes. A source file (*.cpp, *.c++, *.C) contains the definitions.
A header file can be included in a source file using #include directive.
When you define a class in C++, you typically only include the declarations of the member functions (methods in Java lingo), and you put the class definition into a header file. The member function definitions containing the body of each function are typically put outside the class definition and into the source file.
Generally the best thing to do here is to get a book on C++ or C, and to look at some sample code.
Header files (.h) are supposed to contain definitions of classes, methods, and variables. Source file (.cpp) will contain the code. So in your .cpp file you need to include the header file as #include "header-file-name.h".
Then use g++ to compile the .cpp file. Make sure that the path to .h file is correct.
If you are using CodeBlocks or Visual Studio, then just compiling the project and running will do everything for you. You can also add .h or .cpp file from there. You need not worry about anything.
Hope this helps.