Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using #include to include sections of code

Tags:

c++

include

I'm using a 3rd party open-source application that does something I think is strange. I'd like to hear your opinion on whether you think this is wrong / evil / an abomination / etc., or if there is some justifiable reason to do this.

Simply put, they use #include pre-proc directives to include "header files" that include fragments of code. Not prototypes of functions. Not in-line functions. Just sections of code.

Here is a simple example. First the main.cpp file:

#include <iostream>
//Other "normal" includes here...

int main(int argc, char *argv[]) {

  cout << "Initializing program..." << endl;
  #include "parseArgs.h"

  // ... remainder of the program

  cout << "Exiting." << endl;
  return 0;
}

And within the parseArgs.h header file, a small code fragment. Note that this is exactly and only what is in the parseArgs.h file. This is not part of a function. There are no include guards, just the following 4 lines:

argList args(argc, argv);
if(!args.valid()) {
  cout << "Invalid arguments.";
  exit(1);
}

In the real program, there are several of these #include directives, with each one doing another small task.

It seems dangerous and crazy. I don't know why they don't write and call these as functions.

Your ideas and opinions?

like image 945
Madeleine P. Vincent Avatar asked Mar 11 '13 10:03

Madeleine P. Vincent


1 Answers

I think you're talking about OpenFOAM here. The problem that these code snippets solve is that of avoiding the duplication of boilerplate code that many applications in OpenFOAM need. Putting this code in a function won't solve the problem, because the variables declared inside a function are local to its scope. One could perhaps come up with a scheme of base classes that contain these variables as members. But that would just add another layer of indirection that doesn't really solve anything. You're still dependent on variable names (or, if you want to make it clean, getter-names).

Personally, I'm undecided on whether this practice is good or bad. It is how it is, and it is part of the OpenFOAM code culture (or local lingo, if you want). At first sight it's surprising, but one gets used to it pretty fast.

However, unless you are developing OpenFOAM applications/extensions yourself, I would strongly discourage this practice. OpenFOAM is somewhat unique in that it contains virtually hundreds of executables that all require some overlapping boilerplate code that would be hard to maintain otherwise. If you're not in that situation, then don't do it.

like image 101
Michael Wild Avatar answered Sep 20 '22 00:09

Michael Wild