C++, the “Old Fashioned” way

前端 未结 8 1025
孤街浪徒
孤街浪徒 2021-02-04 14:56

I have been learning C++ in school to create small command-line programs.

However, I have only built my projects with IDEs, including VS08 and QtCreator.

I under

8条回答
  •  执笔经年
    2021-02-04 15:49

    I know what Makefiles are, but not how to write them.

    The make syntax is horrible, but the GNU make docs aren't bad. The main syntax is:

     :   
        
        
    

    Which defines commands to build the target from the given dependencies.

    Reading docs and examples is probably how most people learn makefiles, as there are many flavors of make with their own slight differences. Download some projects (pick something known to work on your system, so you can actually try it out), look at the build system, and see how they work.

    You should also try building a simple make (strip out a bunch of the harder features for your first version); I think this is one case where that will give you a much better grasp on the situation.

    I know what gcc does, but not how to use it.

    Again, man g++, info pages, and other documentation is useful, but the main use when you call it directly (instead of through a build system) will be:

    g++ file.cpp -o name            # to compile and link
    g++ file.cpp other.cpp -o name  # to compile multiple files and link as "name"
    

    You can also write your own shell script (below is my ~/bin/c++ simplified) to incorporate $CXXFLAGS so you won't forget:

    #!/bin/sh
    g++ $CXXFLAGS "$@"
    

    You can include any other option as well. Now you can set that environment variable ($CXXFLAGS, the standard variable for C++ flags) in your .bashrc or similar, or redefine it in a particular session, for working without a makefile (which make does do just fine, too).

    Also use the -v flag to see details on what g++ does, including...

    I know what the linker does, but not how to use it.

    The linker is what takes the object files and links them, as I'm sure you know, but g++ -v will show you the exact command it uses. Compare gcc -v file.cpp (gcc can work with C++ files) and g++ -v file.cpp to see the difference in linker commands that often causes the first to fail, for example. Make also shows the commands as it runs them by default.

    You are better off not using the linker directly, because it is much simpler to use either gcc or g++ and give them specific linker options if required.

提交回复
热议问题