Is it bad to use #include in the middle of code?

  • A+

I keep reading that it's bad to do so, but I don't feel those answers fully answer my specific question.

It seems like it could be really useful in some cases. I want to do something like the following:

class Example {     private:         int val;     public:         void my_function() { #if defined (__AVX2__)     #include <function_internal_code_using_avx2.h> #else     #include <function_internal_code_without_avx2.h> #endif         } }; 

If using #include in the middle of code is bad in this example, what would be a good practice approach for to achieve what I'm trying to do? That is, I'm trying to differentiate a member function implementation in cases where avx2 is and isn't available to be compiled.


No it is not intrinsically bad. #include was meant to allow include anywhere. It's just that it's uncommon to use it like this, and this goes against the principle of least astonishment.

The good practices that were developed around includes are all based on the assumption of an inclusion at the start of a compilation unit and in principle outside any namespace.

This is certainly why the C++ core guidelines recommend not to do it, being understood that they have normal reusable headers in mind:

SF.4: Include .h files before other declarations in a file


Minimize context dependencies and increase readability.

Additional remarks: How to solve your underlying problem

Not sure about the full context. But first of all, I wouldn't put the function body in the class definition. This would better encapsulate the implementation specific details for the class consumers, which should not need to know.

Then you could use conditional compilation in the body, or much better opt for some policy based design, using templates to configure the classes to be used at compile time.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: