How do you compile just a .h file in a makefile? - c++

I have a makefile that creates object files for two classes (and main) and one of those classes is just defined in a .h file. In my makefile I have a line that says
FileName.o: FileName.h
g++ -c FileName.h
but when I try to compile it says it can't find FileName.o
Do I have to create FileName.cpp in order to get this to compile?

You are using your class from FileName.h somewhere, aren't you? So at least one of your .cpp files should contain #include "FileName.h", and .h's code will be compiled with this .cpp and you needn't compile .h's code separately.

You don't normally attempt to compile a header (.h) file by itself. Including it into an otherwise empty .cpp file will let you compile it and produce a .o file, but it probably won't do much (if any) real good unless you've put things in the header that don't really belong in a header.

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++ When does class object file get compiled?

I'm new to C++, and having difficulty understanding the steps of class object files getting created and compiled.
Let's say I create 3 files: 1. class header file 2. class cpp file (member function definitions present) 3. main cpp file
/*
When I run the main cpp file which includes the class header file (say as "#include class.h"), when does class cpp file get compiled, object file created, and linked?
The reason why I'm having difficulty is that from the compiler point of view, when it sees the main cpp file, there is only the header definition, no member function definition. However, even in the class header file, there is no class cpp file included. How would compiler know to run the class cpp file when it is not referred to in either class header file and the main cpp file?
*/
Let me clarify my question.
// Maybe I've said things I don't even understand lol.
So, basically I'm trying to run a main function in a say 'main.cpp' file. This 'main.cpp' file includes the 'class.h' header (include "class.h"). How would compiler execute the functions defined in header file when member function is not declared in 'class.h?' All my member function declaration is in 'class.cpp,' which is not included in 'class.h' or 'main.cpp.'
I suspect you're using an IDE, since you mention running cpp files - compilers don't know how to run anything.
Your IDE manages these dependencies for you.
When you press "Run", the IDE will decide which files in your project need compiling, and when the compilation is done it will link all the object files together.
If compilation and linking succeeded, the IDE then launches the executable program.
If you want a better understanding of the concepts, step away from your IDE and do all your compilation and linking on the command line for a while.
(It's not complicated, only tedious.)
You need to compile every .cpp file. Headers; .h files, are just for declarations, means that to let the compiler determine if you use the functions correctly. Each .cpp contains code and should be translated to machine code (.o files). After all these compilations, you need to link them to build the executable so that every function used is contained in the same file. The following commands can help you (using g++ compiler):
$ g++ -c myclass.cpp // produces the myclass.o file
$ g++ -c main.cpp // produces the main.o file
$ g++ -o myapp main.o myclass.o // produces the myapp executable
This is oversimplified for the sake of understanding.

Definitive way to include files on c++ avoiding cyclic dependencies

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.

c++: #include and different file types

I somehow can't grab the idea and reading the documentation hasn't helped me.
My questions are:
When I include a header file #include "general.h", and in the directory of my project there are two files general.h and general.cpp, does it mean that I the precompiler will find the .cpp file automatically?
Can I include files without extentions: #include "general"?
Can I include a file without any header file: #include "general.cpp"?
Can I include a txt file: #include "general.txt"?
I tried this all in Visual Studio 2010. No syntax errors at least. But I'd like to have an explanation. So, I hope you will be kind and help me.
The standard and the compiler don't really care much about whether a file is .cpp or .h or .monkeyface. The concepts behind structuring your source code into implementation and header files are really just accepted ways to help manage your source. Despite this, not structuring your source in the accepted way is often considered to be incorrect or bad C++.
All #include does is tell the preprocessor to include the contents of the file you specify in the current file. It's like copying and pasting the other file into yours. When you say #include "foo.h", it just includes the contents of foo.h and doesn't care about foo.cpp at all - it doesn't even know that it exists (and there's no reason it has to exist).
Structuring your source code in implementation and header files is extremely useful - it avoids problems with dependencies and multiple definitions, and also improves compilation time somewhat. When your code uses another class, you only need to #include the header file for that class. The reason is because your code doesn't need to care about the implementation of the class, it just needs to know what it looks like (its name, members, base class, etc.). It doesn't concern itself with how exactly the member functions are implemented.
The extensions .cpp and .h are merely conventions. Some people prefer to use .hpp for header files. Some people even use .tpp for template implementations. You can name them however you like - yes, you can even include a .txt file. Your compiler probably tries to infer things about files (for example, which language to compile it as) from the file extension, but that is usually overrideable.
So if your main.cpp includes foo.h because it uses class foo, at what point does foo.cpp get involved? Well, in the compilation of main.cpp, it doesn't get involved at all. main.cpp doesn't need to know about the implementation of the class, as we discussed above. However, when compiling your entire program, you will pass each of your .cpp files to the compiler to be compiled separately. That is, you would do something like g++ main.cpp foo.cpp. When foo.cpp is compiled, it will include the headers that it needs to compile.
After each of your .cpp files has been compiled (which involves including the headers that they depend on), they are then linked together. The use of a member function foo::bar() in main.cpp will at this stage be linked to the implementation of foo::bar() that was given in foo.cpp.
The #include directive tells the preprocessor to read the file. That's all.
The preprocessor simply inserts the whole content of the given file when it encounters a #include directive.
No, the precompiler know nothing about the .cpp file
Yes, if the file has no extensions
You can include any file you want. It doesn't mean you will get anything useful out of it.
See point 3. above.
#include is a simple "insert the contents of the given file here" mechanism, so the preprocessor will include exactly the file you specify. If you include a .h file, neither the preprocessor nor the compiler will know about the corresponding .cpp file - each .cpp file is compiled separately (the purpose of the .h files is to inform the compiler of which functions exist outside of the current .cpp file). After compilation, the linker is invoked, and only then are the compiled results of the different .cpp files combined.

C\C++ - Re-using functions across multiple programs

In Python whenever I had a bunch of functions that I wanted to use across multiple programs I'd make another .py file and then just import that wherever I needed it. How would I do that in C/C++? Do I dump both prototype and implementation into an .h file? or do I need to place the function prototypes in the .h file and the implementations in a separate .cpp file with the same name as the .h file and #include the .h wherever I need it?
You need to do a couple of things:
Add the prototype to a header file.
Write a new source file with the function definitions.
In a source file that just wants to use the shared function, you need to add #include "header.h" (replacing header.h with the name of the file from step 1) someplace before you try to call the shared function (normally you put all includes at the top of the source file).
Make sure your build compiles the new source file and includes that in the link.
A couple of other comments. It's normal to have foo.h as the header for the foo.c but that is only a style guideline.
When using headers, you want to add include guards to protect against the multiple include issue.
In C/C++ we usually put declarations in .h files and implementation in .c/cpp files.
(Note: there're many other ways, for example the include, templates, inline, extern, ... so you may find some code only in header files or only in c/cpp files - for example some of the STL and templates.)
Then you need to "link" the file with your program, which works like the "import" in Python interpreter but actually works in static linking object files together into a single executable file.
However the "link" command and syntax depends on your compiler and OS linker. So you need to check your compiler for more information, for example "ld" on UNIX and "link.exe" on DOS/Windows. Moreover, usually the C compiler will invoke the linker automatically.
For example, say you have 2 files: a.c and b.c (with a.h and b.h), on gcc:
gcc -o a.out a.c b.c
On MSVC:
cl a.c b.c
There are two ways to approach this that differ only slightly. As others have said, the first steps are:
-Create a header file which contains your function prototypes. You'll want to mark this with
# ifndef myheader_h
# define myheader_h
// prototypes go here...
# endif
to prevent problems with multiple inclusions.
-Create a .c file which contains the actual definitions.
Here's where the solutions branch.
If you want to include the source directly in your project, make the .c file part of your compilation stage as well as your link stage.
However, if you really plan on using this across multiple projects, you'll probably want to compile this source file independently, and reference the object file from your other projects. This is loosely what a "library" is, though libraries may consist of multiple object modules - each of which has been compiled but not yet linked.
update
Someone pointed out that this really only keeps the header from being included in a single cpp file. News flash: that's all you need to do.
Compilers treat each cpp file individually. The header files included by each cpp source file tell the compiler, "hey! This thing is defined in another source file! Assume references that match this prototype are A-OK and keep moving on."
The LINKER, on other other hand, is responsible for fixing up these references, and IT will throw a fit if the same symbol is defined in multiple object files. For that to happen, a function would have to be defined in two separate source files - a real definition with a body, not just an extern prototype - OR the object file that contains its body/definition would have to be included in the link command more than once.
Re:"inline"
Use of "inline" is meant as an optmization feature. Functions declared as inline have their bodies expanded inline at each place where they are called. Using this to get around multiple definition errors is very, very bad. This is similar to macro expansion.
See Francis's answer. The sentence that you wrote, "or do I need to place the function prototypes in the .h file and the implementations in a separate .cpp file with the same name as the .h file and #include the .h wherever I need it?", is pretty-much correct. You don't have to do things exactly this way, but it works.
It's up to you how you do this, The compiler doesn't care. But if you put your functions in a .h file, you should declare them __inline otherwise if you include the header file in more than one .cpp file, you will have multiply defined symbols.
On the other hand, if you make them __inline, you will tend to get a copy created in each place that you use the function. This will bloat the size of your program. So unless the functions are quite small, it's probably best to put the functions in a .cpp and create a parallel .h with function prototypes and public structures. This is the way most programmers work.
On the other hand, in the STL (Standard Template Library), virtually all of the code is in header files. (without the .h extension)