C++Guns – RoboBlog

27.07.2018

C++ Guns: use FORTRAN debug techniques in C++

Filed under: Allgemein — Tags: , — Thomas @ 15:07

On of the first things one learn about FORTRAN: you can very easy write stuff to files without getting worried about file creation of filenames.
Just write to a random number, the file handle. You can do this everywhere in the code. The output is append to the file. And the file gets automatic cleaned on program start.
Here is one example:

program debug
  integer :: x
  x = 1
  write(1001,*) "This is string", x
  write(1001,*) "The End"
end program

$ gfortran debug.f90
$ ./a.out
$ cat fort.1001
This is string 1
The End

As you can see, the file handle number get prefixed with "fort.". This is pretty nice for some nasty debug session, so lets do this with C++!

The implementation in C++ is surprisingly easy, just a single line of code and we are done:

#include <fstream>

template<int fhdl>
inline std::ofstream& write() {
    static std::ofstream ostrm("cpp."+std::to_string(fhdl), std::ios::out);
    return ostrm;
}

int main() {
    int x = 1;
    write<1001>() << "This is string " << x << "\n";
    write<1001>() << "The End\n";
}

$ g++ debug.cpp
$ ./a.out
$ cat cpp.1001
This is string 1
The End

The file handle number is passed as template parameter. I guess it is always know at compile time during the debug session. Then the write() function simply returns a reference to a static standard ofstream object. Which is created during the first call to write(). The created files are prefixed with "cpp." And you can use this with any custom type with overloaded operator<<. Thats all.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress