Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
This might be a duplicate question but all of my search results talk about not putting using into a header file, which is not my question. I have read up on this and understand why you should not place using inside of a header file.
I am new to C++ and am trying to make sure I am learning/using best practices. I know header files are meant for defining classes, structs and the like and should never "do" anything. Does this include std::cout? Is that considered doing something? What I mean is, is it okay to print output from a header file, or should i return data to my *.cpp file and do the output from there? Or does this not really matter?
There is nothing wrong in principle with doing things in header file. Indeed, header only libraries are quite popular in C++ nowadays. In some cases (such as templates) doing things in header file is the only way to go.
The art of splitting definitions between header file and .cpp file is often a judgment call. Generally, when you define functions in header file, you might hope for better performance (since inlining would be more easily achieved), but you might end up with larger codebase (depending on linker behavior), and you are likely to increase your compilation time.
Instead of asking for best practices, I wholeheartedly suggest you understand what are the mechanics at play there, and make a conscious choice yourself.
IMHO ...
Use of std::cout in any file in a library is a symptom of poor design. If you need to output something, provide the interface for the client code to pass a ostream or an ostream-like object that supports inserting data to it.
Use of std::cout in an application-specific file, be it a header file or a .cpp file, is perfectly fine.
Is std::cout in a header file bad practice?
Not necessarily. For example, you might have a function which outputs character sequence into a stream. It would be useful to let the client of the function to choose which stream to use, so the function accepts the stream as an argument. It might make a lot of sense for the function to have the default behaviour of streaming to the standard output stream. Therefore you might have a function declaration in a header such as:
void stream_fancy_stuffs(std::ostream& output_stream = std::cout);
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I was wondering (for code security reasons) - can user of c++ library use library's classes, function calls, variables that he does not know because he has only a single header with the library?
If he would guess names for classes and calls by looking for text in library file, could he compose a header file that would allow him to use the code?
Firstly, a header file is really just for convenience. There's nothing stopping a user from recreating the header file using the library's documentation (or even just by reverse engineering the library), and so there's also nothing stopping them from adding parts of the library's public interface that were missed out of the header.
But the header should contain the whole public interface, otherwise what's the point of it? Furthermore, libraries should usually be designed such that anything else has internal linkage and is not exported. Though not impossible, it is more difficult to use these because the runtime (or static) linker will not resolve your hand-crafted declarations as referring to the symbols in the private part of the library. In normal use, they're considered to be hidden.
This is certainly not a "security" measure as ultimately anything can be hacked away, but a library's internals are generally considered to be safely tucked away in terms of easy access.
If you wanted to prevent a bad actor from gaining any access to your library's internals, you would have to do several things:
Decide how bad an actor you want to resist
Decide what form of attack you want to resist
Decide how strong an attack you want to resist
Decide how much usability you want to sacrifice in the attempt
Realise that it's entirely futile and stop trying
Yes it is possible, at least for accessing global variables that have external linkage. Imagine:
foo.cpp
int foo = 42;
main.cpp
#include <iostream>
extern int foo;
int main() {
std::cout << foo;
}
There is no header file connecting main.cpp to foo.cpp but since we know the name foo we can use extern in main.cpp to tell the compiler it is defined somewhere else and the linker will give us access to it.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
One of my previous colleagues wrote a huge header file which has around 100 odd structures with inline member function definitions. This structure file is included in most class implementations(cpp files) and header files(don't know why my colleague didn't use forward declarations)
Not only it is a nightmare to read such a huge header file, but its difficulty to track problems due to compiler complaining of multiple definitions and circular references now and then. Overall compilation process is also really slow.
To fix many such issues, I moved inclusion of this header file from other header files to cpp files (wherever possible) and used forward declarations of only relevant structures. Still I continue to get strange multiple definition errors like "fatal error LNK1169: one or more multiply defined symbols found".
I am now contemplating whether I should refactor this structure header file and separate the structure declaration and definition in separate h/cpp files for each and every structure. Though it will be painful and time consuming to do this without refactoring tools in Visual Studio, is this a good approach to solve such issues ?
PS: This question is related to following question : Multiple classes in a header file vs. a single header file per class
When challenged with a major refactoring like this, you will most likely do one of the following approaches: refactor in bulk or do this incrementally.
The advantage of doing it in bulk is that you will go through the code very fast (compared to incrementally) however if you end up with some mistake, it can take quite a lot of time before you get it fixed.
Doing this incrementally and splitting of the classes one by one, you reduce the risk of time-consuming mistakes, however it will take some more time.
Personally, I would try to combine the 2 approaches:
Split off every class, one-by-one (top-to-bottom) into different translation units
However keeping the major include file, and replacing all moved classed by includes
Afterwards you can remove the includes to this major header file and replace them by the singular classes
Finally, remove the major header file
Something that I've already found useful for creating self-sufficient header files is to precompile your headers. This compilation will fail when you haven't included the right data.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I was wondering if there are any official recommendations regarding the use of define in c++ language, precisely is it best to define in your header or your source file?
I am asking this to know if there are any official standards to live by, or is it just plain subjective... I don't need the whole set of standards but the source or a link to the guidelines, will suffice.
LATER EDIT:
What is the explanation of the fact that const and constexpr have become the status quo, I am referring to define used as means of avoiding repetitive typing, it is clear in my mind that programmers should use the full potential of the c++ oop compiler. On the other hand, if it is so feared, why not remove it altogether? I mean, as far as I understand, define is used solely for conditional compilation, especially, as in making the same code work on different compilers.
Secondary, tiny question, the potential for errors is also the main reason why java doesn't have true C-style define?
A short list of #define use guidelines for C++, points 2, 4, 6 and 7 actually address the question:
Avoid them
Use them for the the common "include guard" pattern in header files
Otherwise, don't use them, unless you can explain, why you are using #define and not const, constexpr, or an inline or a template function, etc, instead.
Use them to allow giving compile time options from compiler command line, but only when having the option as run-time option is not feasible or desirable.
Use them when whatever library you are using requires using them (example: disable assert() function )
In general, put everything in the most narrow possible scope. For some uses of #define macros, this means #define just before a function in .cpp file, then #undef right after the function.
The exact use case for #define determines if it should be in .h or in .cpp file. But note that most use cases are actually in violation of 3. above, and you should actually not use #define.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I found several places where it is discussed whether it is better to put definitions in headers or not (e.g. here). However, I could not find something like a "guide to header-only code". The answer to the linked question mentions some downsides:
increased compile time
not possible to have circular dependencies
no (simple) global objects
But is that all?
What are the consequences of putting (all) code in the header?
Am I save if I use header guards, or are there other pitfalls?
The reason I am asking this is the following:
I am in a situation where I think it would easiest to put all the code in my header files. It is a (rather small) collection of classes and functions that is supposed to be included by others in their code. It is supposed to be used in different environments and in different frameworks. At the moment, I do not see why I should build my code (into a lib), when the one using it can simply include the header she/he needs and compile it. However, independent of this project I always have a "bad feeling" when putting code in headers, even if none of the 3 points I mentioned above matters. Would be really nice if someone could shed some light on this for me so I can make the decision where to put the code on a more reasonable basis.
Starting from my personal experience, I usually put only one-line functions (getters and setters) in the header file because all other function bodies will make the header file difficult to read and understand at a glance.
Moreover if your project needs to include the header file multiple times (and you wrote function code in it), you would have an icreasing compile times since all code has to be processed every time it is included by the compiler.
There are several examples of brilliant libraries implemented mostly in header files, e.g. the std library or boost. In particular, if you want to distribute a template library, you have you have no real alternative.
Worst consequences of such an approach, imho, are:
exploding of compilation time: every edit you make to your code, you'll have to rebuild all files that include that header; this is a really serious issue, unless you keep using the ".h"/".cpp" approach while developing and then rearrange your code into the header just at the end
binary code bloat: all your functions will have to be declared "inline", so you may have a performance improvement but you may (1) also have a replication of binary code every time you use a function
(1) see Klaus comment and inline description at cppreference.com (quoted below):
The intent of the inline keyword is to serve as an indicator to the optimizer that inline substitution of the function is preferred over function call, that is, instead of executing the call CPU instruction to transfer control to the function body, a copy of the function body is executed without generating the call. This avoids extra overhead created by the function call (copying the arguments and retrieving the result) but it may result in a larger executable as the code for the function has to be repeated multiple times.
Since this meaning of the keyword inline is non-binding, compilers are free to use inline substitution for any function that's not marked inline, and are free to generate function calls to any function marked inline. Those choices do not change the rules regarding multiple definitions and shared statics listed above.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Where is it customary to write the in-code documentation of classes and methods?
Do you write such doc-blocks above the corresponding class/method in the header (.hpp) file, or within the source (.cpp) file?
Is there a widely respected convention for such things? Do most C++ projects do it one way rather than the other?
Or should documentation be written on the two sides (i.e. in the .hpp and the .cpp files), maybe with one short description one one side and a longer one on the other side?
Most importantly, are there any practical considerations that makes it more convenient to write it one way rather than the other way ? (E.g. the use of automatic documentation parsers and generators like Doxygen...)
Both:
Describe the API design and usage in the header: that's your public interface for clients.
Describe the implementation alternatives / issues and decisions in the implementation: that's for yourself - later - and other maintainers/enhancers, even someone reviewing the design as input to some next-gen system years hence.
Comment anything that's not obvious, and nothing that is (unless your documentation tool's too stupid to produce good documentation without).
Avoid putting implementation docs in the headers, as changing the header means makefile timestamp tests will trigger an unnecessary recompilation for client apps that include your header (at least in an enterprise or commercial library environment). For the same reason, aim to keep the header documentation stable and usable - good enough that you don't need to keep updating it as clients complain or ask for examples.
If you make a library, you typically distribute the compiled library and the header files. This makes it most useful to put documentation in the header files.
Most importantly, are there any
practical considerations that makes it
more convenient to write it one way
rather than the other way ?
Suppose that you want to add a clarification to one of your comments without changing the code. The problem is that your build system will only see that you changed the file, and unnecessarily assume that it needs to be recompiled.
If the comments are in the .cpp file, it will just recompile that one file. If the comments are in the .hpp file, it will recompile every .cpp file that depends on that header. This is a good reason to prefer having your comments in the .cpp files.
(E.g. the
use of automatic documentation parsers
and generators like Doxygen...)
Doxygen allows you to write your comments either way.
Again, both. As for the public documentation, it is nice to be in the .h with a format extractable with Doxygen, for example, as other commented. I like very much the Perl way of documenting things. The .pl (or .pm) file includes documentation in itself that can be extracted using a tool similar to what Doxygen does for C++ code. Also, Doxygen allows you to create several different pages, that allow you to include user manuals, etc., not just documenting the source code or API. I generally like the idea of a self-contained .h/.hpp file in the philosophy of literate programming.
I personally like documentation in the header files. However, there are some that believe that documentation should be put in the source files. The reason being that when something changes, the documentation is right there reminding you to update it. I somewhat agree, as I personally have forgotten to update the Doxygen comments in the header when I changed something in the source files.
I still prefer the Doxygen comments to be in the header file for aesthetic reasons, and old habits are hard to change. I've tried both and Doxygen offers the flexibility of documenting either in source or header files.