How to compile C++ under Ubuntu Linux?

前端 未结 11 1742
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 08:35

I cut&pasted the below code from a previous question into a file called \"avishay.cpp\" and then ran

gcc avishay.cpp

only to get the f

相关标签:
11条回答
  • 2020-12-09 09:03

    You should use g++, not gcc, to compile C++ programs.

    For this particular program, I just typed

    make avishay
    

    and let make figure out the rest. Gives your executable a decent name, too, instead of a.out.

    0 讨论(0)
  • 2020-12-09 09:04

    To compile source.cpp, run

    g++ source.cpp
    

    This command will compile source.cpp to file a.out in the same directory. To run the compiled file, run

    ./a.out
    

    If you compile another source file, with g++ source2.cpp, the new compiled file a.out will overwrite the a.out generated with source.cpp

    If you want to compile source.cpp to a specific file, say compiledfile, run

    g++ source.cpp -o compiledfile
    

    or

    g++ -o compiledfile source.cpp
    

    This will create the compiledfile which is the compiled binary file. to run the compiledfile, run

    ./compiledfile
    

    If g++ is not in your $PATH, replace g++ with /usr/bin/g++.

    0 讨论(0)
  • 2020-12-09 09:06

    Yes, use g++ to compile. It will automatically add all the references to libstdc++ which are necessary to link the program.

    g++ source.cpp -o source
    

    If you omit the -o parameter, the resultant executable will be named a.out. In any case, executable permissions have already been set, so no need to chmod anything.

    Also, the code will give you undefined behaviour (and probably a SIGSEGV) as you are dereferencing a NULL pointer and trying to call a member function on an object that doesn't exist, so it most certainly will not print anything. It will probably crash or do some funky dance.

    0 讨论(0)
  • 2020-12-09 09:06

    even you can compile your c++ code by gcc Sounds funny ?? Yes it is. try it

    $  gcc avishay.cpp -lstdc++
    

    enjoy

    0 讨论(0)
  • 2020-12-09 09:08

    Update your apt-get:

    $ sudo apt-get update
    $ sudo apt-get install g++
    

    Run your program.cpp:

    $ g++ program.cpp
    $ ./a.out
    
    0 讨论(0)
提交回复
热议问题