I have found some threads that explain why C++ separates .cpp and .h files (e.g. here). I'd be interested to know if it causes any problem if I don't separate them. I don't want to share the object files, so what's the benefit of the separation on a small project? If it just slows down the compilation time, it's not a big deal in my opinion. I want to re-implement a Java program in C++, so to me it seems much easier to keep a class in one file only. Example:
// Hello.cpp
#ifndef HELLO_20091218
#define HELLO_20091218
#include <iostream>
#include "Utils.cpp"
class Hello
{
public:
void start()
{
std::cout << Utils::nrand(100) << "\n";
// Utils and all other classes are written in a similar way
}
};
#endif
There is a thing that troubles me. "Defining a member function inside the class asks the implementation to expand calls to it inline." So if I do like this, everything is marked inline implicitly. Will it cause a larger executable or any other disadvantages?
In C and C++ the smallest unit of compilation is the file. If you just don't use header files and include everything in your "main" file, everytime you change something your whole program would have to be recompilled. For larger applications this can be a very good argument for separation of header and implementation. Also if another part of your application would live in another binary executable and you wan't to reuse classes you are safe with header files while you will get alot of overhead without them.
If you don't care about those things (You'll regret that.) there is no need in separate header files for you.
About the inlining: The compiler will inline a lot of functions (sometimes even whole classes, so to speak) anyway, even if you don't ask it to do that. Inlining is generally a benefit for performance. There are corner cases (large size of the executable can resolut in slower execution) but those are fairly unusual.
That's really two questions.
Right now, what you've shown above as "Hello.cpp" looks like a header, complete with an include guard. The compiler doesn't really care what name you give your header, but including a .cpp file will be confusing (at best) to anybody looking at your code. If you're compiling this on its own, the include guard (at least) should probably go -- while it doesn't cause a real problem, it's pointless and confusing at best.
Yes, member functions that you define inside the class definition are implicitly inline. That doesn't mean the compiler is required to generate inline code for them though. It's basically just a hint to the compiler, and most compilers decide on their own whether to generate inline code, based mostly on what the function contains, not where it's defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With