PrevNext

C++ With the Command Line

Authors: Benjamin Qi, Hankai Zhang, Anthony Wang, Nathan Wang, Nathan Chen

OS-specific instructions for installing and running C++ via the command line.

Resources
CPHwhat compiling a simple program looks like

Command Line Basics

This section is not complete.

Feel free to file a request to complete this using the "Contact Us" button.

what is the command line? :P

This section is not complete.

Feel free to file a request to complete this using the "Contact Us" button.

link more resources

Linux

Resources
William Shotts

Mac

Should be mostly the same as Linux ...

Open the Terminal application and familiarize yourself with some basic commands. Upgrade to zsh if you haven't already.

Resources
Jim Hoskins
Rahul Saigalkeyboard shortcuts / terminal commands
Armin Briegel

Windows

This section is not complete.

Feel free to file a request to complete this using the "Contact Us" button.

Installing GCC

USACO (and most contests) use GCC's g++ to compile and run your code. You'll need g++ specifically to use the #include <bits/stdc++.h> header file within the template provided in Code Conventions; see C++ Tips & Tricks for details.

On Linux

GCC is usually preinstalled on most Linux distros. You can check if it is installed with

whereis g++

If it is not preinstalled, you can probably install it using your distro's package manager.

On Windows

Resources
Jetbrainssetting up Cygwin, MinGW, WSL, or MSVC

MinGW (Minimalist GNU for Windows)

Resources
MicrosoftMinGW
Rose-Hulman
  1. First, download and run the MinGW installer.
  2. Once it's installed, open the MinGW Installation Manager, click on Basic Setup on the left, and select mingw32-gcc-g++-bin for installation.

WSL 2 (Windows Subsystem for Linux 2)

This is what I (Anthony) personally use, although it may be more difficult to properly set up.

Resources
Microsoftdifficult for beginners

If you want to code in (neo)vim, you can install WSL and code through WSL bash.

On Mac

  1. Install XCode command line tools.

    xcode-select --install
    

    If you previously installed these you may need to update them:

    softwareupdate --list # list updates
    softwareupdate -i -a # installs all updates
    

    After this step, clang should be installed (try running clang --version in Terminal).

  2. Install Homebrew.

  3. Install gcc with Homebrew.

    brew install gcc
    

    According to this if brew doesn't seem to finish for a long time then

    brew install gcc --force-bottle
    

    probably suffices.

  4. You should be able to compile with g++-#, where # is the version number (ex. 9). Running the following command

    g++-9 --version
    

    should display something like this:

    g++-9 (Homebrew GCC 9.2.0_2) 9.2.0
    Copyright (C) 2019 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    
  5. If you want to be able to compile with just g++, create a symbolic link as mentioned here.

    cd /usr/local/bin
    ln -fs g++-9 g++
    

    g++ --version should now output the same thing as g++-9 --version.

C++ with the Command Line

Basics of Compiling & Running

Consider a simple program such as the following, which we'll save in name.cpp.

1#include <iostream>
2using namespace std;
3
4int main() {
5 int x; cin >> x;
6 cout << "FOUND " << x << "\n";
7}

It's not hard to compile & run a C++ program. First, open up Powershell on Windows, Terminal on Mac, or your distro's terminal in Linux. We can compile name.cpp into an executable named name with the following command:

g++ name.cpp -o name

Then we can execute the program:

./name

If you type some integer and then press enter, then the program should produce output. We can write both of these commands in a single line:

g++ name.cpp -o name && ./name

Redirecting Input & Output

If you want to read input from inp.txt and write to out.txt, then use the following:

./name < inp.txt > out.txt

See Input & Output for how to do file input and output within the program.

Compiler Options (aka Flags)

Use compiler flags to change the way GCC compiles your code. Usually, we use something like the following in place of g++ name.cpp -o name:

g++ -std=c++17 -O2 name.cpp -o name -Wall

Explanation:

  • -O2 tells g++ to compile your code to run more quickly (see here)
  • -std=c++17 allows you to use features that were added to C++ in 2017. USACO currently uses -std=c++11.
  • -Wall checks your program for common errors. See Debugging for more information.

You should always compile with these flags.

Mac-Specific

Adding Shortcuts

For Users of Linux & Windows

The process is similar for Linux. If you're on Windows, you can use an IDE to get these shortcuts, or you can install WSL (mentioned above).

Of course, retyping the flags above can get tedious. You should define shortcuts so you don't need to type them every time!

First, create your .zshenv if it doesn't already exist.

touch ~/.zshenv

Open your .zshenv with TextEdit.

open -a TextEdit ~/.zshenv

or some text editor (ex. sublime text with subl).

subl ~/.zshenv

You can add aliases and functions here, such as the following to compile and run C++ on Mac.

co() { g++ -std=c++17 -O2 -o $1 $1.cpp -Wall; }
run() { co $1 && ./$1 & fg; }

Now you can easily compile and run name.cpp from the command line with co name && ./name or run name. Note that all occurrences of $1 in the function are replaced with name.

What is & fg for?

Let prog.cpp denote the following file:

1#include <iostream>
2#include <vector>
3using namespace std;
4
5int main() {
6 vector<int> v;
7 cout << v[-1];
8}

According to the resource above, the & fg is necessary for getting zsh on Mac to display crash messages (such as segmentation fault). For example, consider the running the first prog.cpp above with run prog.

If & fg is removed from the run command above then the terminal displays no message at all. Leaving it in produces the following (ignore the first two lines):

[2] 30594
[2]  - running    ./$1
zsh: segmentation fault  ./$1

Measuring Time & Memory Usage

For example, suppose that prog.cpp consists of the following:

1#include <bits/stdc++.h>
2using namespace std;
3
4const int BIG = 1e7;
5int a[BIG];
6
7int main() {
8 int sum = 0;
9 for (int i = 0; i < BIG; ++i) sum += a[i];
10 cout << sum;

Then co prog && gtime -v ./prog gives the following:

  Command being timed: "./prog"
  User time (seconds): 0.01
  System time (seconds): 0.01
  Percent of CPU this job got: 11%
  Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.22
  Average shared text size (kbytes): 0
  Average unshared data size (kbytes): 0
  Average stack size (kbytes): 0
  Average total size (kbytes): 0
  Maximum resident set size (kbytes): 40216
  Average resident set size (kbytes): 0
  Major (requiring I/O) page faults: 91
  Minor (reclaiming a frame) page faults: 10088
  Voluntary context switches: 3
  Involuntary context switches: 38
  Swaps: 0
  File system inputs: 0
  File system outputs: 0
  Socket messages sent: 0
  Socket messages received: 0
  Signals delivered: 0
  Page size (bytes): 4096
  Exit status: 0

Note that 10710^7 integers require 4107103400004\cdot 10^7\cdot 10^{-3}\approx 40000 kilobytes of memory, which is close to 4021640216 in the above output as expected.

Adjusting Stack Size

Let A.cpp denote the following program:

1#include <iostream>
2using namespace std;
3
4int res(int x) {
5 if (x == 200000) return x;
6 return res(x+1);
7}
8
9int main() {
10 cout << res(0) << "\n";

If we compile and run this with g++ A.cpp -o A && ./A, this outputs 200000. However, changing 200000 to 300000 gives a segmentation fault. Similarly,

1#include <iostream>
2using namespace std;
3
4int main() {
5 int arr[2000000];
6 cout << arr[0] << "\n";
7}

runs, but changing 2000000 to 3000000 also gives a segmentation fault. This is because the stack size on Mac appears to be limited to 8 megabytes by default.

Resources
Wikipediaexplanation of the issue

Warning!

This matters particularly for contests such as Facebook Hacker Cup where you submit the output of a program you run locally.

Method 1

ulimit -s 65532 will increase the stack size to about 64 MB. Unfortunately, this doesn't work for higher numbers.

Method 2

Resources
CFlooks like people complain about FHC every year!

To get around this, we can pass a linker option. According to the manual for ld (enter man ld in Terminal), the option -stack_size size does the following:

Specifies the maximum stack size for the main thread in a program. Without this option a program has a 8MB stack. The argument size is a hexadecimal number with an optional leading 0x. The size should be a multiple of the architecture's page size (4KB or 16KB).

So including -Wl,-stack_size -Wl,0x10000000 as part of your compilation command will set the maximum stack size to 16716^7 bytes \approx 256256 megabytes, which is usually sufficient. However, running the first program above with 200000 replaced by 1e7 still gives an error. In this case, you can further increase the maximum stack size (ex. by adding another 0 to the end).

Module Progress:

Give Us Feedback on C++ With the Command Line!

PrevNext