I have a bunch of .cpp
files which together process similar data files but of various sizes. For the larger data files I want to do some timing studies on the functions inside the .cpp files.
I would like to suppress the output the results for these big data sets, and only print the timing results. For smaller data sets, I would like to print to the screen to verify algorithm/code correctness.
Rather than repeatedly commenting/uncommenting out the appropriate cout
statements and recompiling , I would like to use command line arguments (or some other technique) to selectively suppress output.
Any suggestions? The naive one I can think of is use argc
and argv
, but I am not sure if they are global variables which can be used by functions across different files.
Your intuition is correct -- use the argc
and argv
values passed into your main
function -- but they are not global variables. You need to make your information global somehow: I'd recommend parsing the arguments once, and keeping a set of global flags that can easily be queried.
For example:
// In a common header file that gets included in each source file
extern bool g_bFlag1;
extern bool g_bFlag2;
...
// In your main source file
bool g_bFlag1 = false;
bool g_bFlag2 = false;
...
int main(int argc, char **argv)
{
// Parse command line and store results in global flags
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "--flag1") == 0)
g_bFlag1 = true;
else if (strcmp(argv[i], "--flag2") == 0)
g_bFlag2 = true;
else
; // etc.
}
}
// In any other source file:
if (g_bFlag1)
{
// do stuff if and only if g_bFlag1 is set
}
Then you can pass --flag1
on the command line. For more complicated argument parsing, I'd suggest using a library such as GNU getopt.