How to auto-include all headers in directory

前端 未结 10 3204
被撕碎了的回忆
被撕碎了的回忆 2021-02-20 12:32

I\'m going through exercises of a C++ book. For each exercise I want to minimize the boilerplate code I have to write. I\'ve set up my project a certain way but it doesn\'t seem

10条回答
  •  失恋的感觉
    2021-02-20 12:53

    Don't use one main.cpp which you modify for each exercise. This solution makes use of make's builtin rules, so you only have to type make e0614 and it will generate e0614.cpp, compile, and link it. You can customize each .cpp file (they won't be regenerated as written below) and maintain all of that history to refer to as you complete exercises, rather than erasing it as you move from one to the next. (You should also use source control, such as Mercurial.)

    Makefile

    e%.cpp:
            ./gen_ex_cpp $@ > $@
    

    You can generate boilerplate code with scripts, because you don't want it to be tedious either. There are several options for these scripts—and I use a variety of languages including C++, Python, and shell—but the Python below is short and should be simple and clear enough here.

    Sample generate script

    #!/usr/bin/python
    import sys
    args = sys.argv[1:]
    if not args:
      sys.exit("expected filename")
    name = args.pop(0).partition(".")[0]
    if args:
      sys.exit("unexpected args")
    upper_name = name.upper()
    print """
    #include "%(name)s.hpp"
    int main() {
      %(upper_name)s ex;
      ex.solve();
      return 0;
    }
    """ % locals()
    

提交回复
热议问题