aboutsummaryrefslogtreecommitdiff
path: root/content/1_Intro/Running_Code.mdx
blob: fc4da14a0788847981995f8213e7283707552012 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
---
id: running-code
title: Running Code
author: Benjamin Qi, Hankai Zhang, Anthony Wang, Nathan Wang, Nathan Chen
description: Options for running your language of choice.
prerequisites:
 - choosing-lang
---

Please let us know if these installation instructions do not work for you.

# Running Code Online

The easiest way to run your code is to run it on an online website. You don't need to install anything. This option is nice for testing small code snippits.

<Warning>

If the website you are using goes down, you may be left without a way to run your code, so even if you primarily use this method, have a offline backup ready! (See below)

</Warning>

- [OnlineGDB](https://www.onlinegdb.com/)
  - C++, Python
  - online compiler with embedded GDB debugger
  - supports files and file I/O
  - can be buggy sometimes
- [CSAcademy](https://csacademy.com/workspace/)
  - C++, Python, Java
  - pretty nice (unless you get "Estimated Queue Time: ...")
  - "saved locally" will **not** save your code if you close the tab, press Command-S to save.
- [Ideone](http://ideone.com/)
  - C++, Python, Java
  - okay ... has the bare minimum you need
  - sometimes erases your code when you first create it (so get in the habit of copying your code first)

<Warning>

If you use Ideone during an online contest (such as a Codeforces round), you **must** ensure that your code is set to be private. **You might be punished for cheating if another person finds and copies your code during the contest, even if you never intentionally provide the code to anyone.**

Even if you are not doing an online contest, you might want to set your code to be private for other reasons.

</Warning>

You can also share code with [pastebin](https://pastebin.com/) or [hastebin](https://hastebin.com/).

# Offline, Using Command Line


<LanguageSection>

<CPPSection>

You can run your C++ programs from the command line and use a text editor of your choice. Read below for different options to create and run C++ programs.

## Text Editors

<Resources>
  <Resource title="Sublime Text 3" url="https://www.sublimetext.com/" starred>
    Fast, lightweight. Unlimited free evaluation period, though it will repeatedly ask you to purchase a license.
  </Resource>
  <Resource title="Atom" url="https://atom.io/">
    From the makers of Github.
  </Resource>
  <Resource title="Vim" url="https://www.vim.org/">
    Classic text editor, usually preinstalled on Linux.
  </Resource>
</Resources>

Vim is probably the easiest way to print syntax-highlighted code on Mac, see the response to [this post](https://stackoverflow.com/questions/1656914/printing-code-with-syntax-highlighting).

### Sublime Text Notes (Ben)

- I prefer the **Mariana** color scheme in place of the default.
  - open command palette (Cmd-Shift-P) -> change color scheme
- [`subl` symlink](https://www.sublimetext.com/docs/3/osx_command_line.html)
  - Using `/usr/local/bin/subl` instead of `~/bin/subl` worked for me on OS X Mojave.
- [Package - Sublime Linter (GCC)](https://packagecontrol.io/packages/SublimeLinter-gcc)
  - highlights compilation errors and warnings from `-Wall`
- [Package - Fast Olympic Coding](https://github.com/Jatana/FastOlympicCoding) (I don't use)
  - test manager can be useful
  - linting is covered by the above
  - stress testing is covered in "Debugging"
  - can't get debug to work

<!--    - [Editing Build Settings](https://stackoverflow.com/questions/23789410/how-to-edit-sublime-text-build-settings)
    - no need to do this if you just use command line to compile & run -->



## 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

### [MinGW](http://mingw.org/)

First, download and run the [MinGW installer](https://osdn.net/projects/mingw/downloads/68260/mingw-get-setup.exe/). Once it's installed, open the MinGW Installation Manager, click on Basic Setup on the left, and select `mingw32-gcc-g++-bin` for installation.

[Adding MinGW to PATH](https://www.rose-hulman.edu/class/csse/resources/MinGW/installation.htm)

### Windows Subsystem for Linux (WSL)

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

[VSCode Docs for WSL](https://code.visualstudio.com/docs/cpp/config-wsl) (difficult for beginners)

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

- Note that WSL has a max stack size of 64MB; I am unsure if this limitation is resolved yet.
- Note that WSL/vim clipboard integration is imperfect.

## On Mac

[Clang](https://en.wikipedia.org/wiki/Clang) is the default compiler for Mac OS X, but you should use [GCC](https://en.wikipedia.org/wiki/GNU_Compiler_Collection)'s `g++` since that's what [USACO](http://www.usaco.org/index.php?page=instructions) uses to compile your code.

### Installation

1.  Open the **Terminal** application and familiarize yourself with some basic commands.

    <Resources>
      <Resource
        source="Jim Hoskins"
        title="Intro to OS X Command Line"
        url="https://blog.teamtreehouse.com/introduction-to-the-mac-os-x-command-line"
        starred
      ></Resource>
      <Resource
        source="Rahul Saigal"
        title="Mac Terminal Cheat Sheet"
        url="https://www.makeuseof.com/tag/mac-terminal-commands-cheat-sheet/"
        starred
      ></Resource>
    </Resources>

2.  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
    ```

3.  Install [Homebrew](https://brew.sh/).

4.  Install `gcc` with Homebrew.

    ```
    brew install gcc
    ```

    According to [this](https://stackoverflow.com/questions/30998890/installing-opencv-with-brew-never-finishes) if `brew` doesn't seem to finish for a long time then

    ```
    brew install gcc --force-bottle
    ```

    probably suffices.

5.  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.
    ```

6. If you want to be able to compile with just `g++`, create a symbolic link as mentioned [here](https://stackoverflow.com/questions/28970935/osx-replace-gcc-version-4-2-1-with-4-9-installed-via-homebrew/28982564#28982564).

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

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

## Running With the Command Line

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

```cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    int x; cin >> x;
    cout << "FOUND " << x << "\n";
}
```

It's not hard to [compile & run a C++ program](https://www.tutorialspoint.com/How-to-compile-and-run-the-Cplusplus-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](./io) for how to do file input and output within the program.

### [Compiler Options (aka Flags)](https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html)

Use [compiler flags](https://developers.redhat.com/blog/2018/03/21/compiler-and-linker-flags-gcc/) 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](https://www.rapidtables.com/code/linux/gcc/gcc-o.html))
- `-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](./debugging) for more information.

You should always compile with these flags.

### Adding Shortcuts (Mac and Linux only)

<Info title="Windows Users">

If you're on Windows, you can use an IDE to get these shortcuts, or you can install WSL (mentioned above).

</Info>

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

<Resources>
  <Resource source="Jonathan Suh" url="https://jonsuh.com/blog/bash-command-line-shortcuts/" title="Aliases in Terminal" starred></Resource>
</Resources>

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++.

```
co() { g++ -std=c++17 -O2 -o $1 $1.cpp -Wall -Wextra -Wshadow; }
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`.


</CPPSection>

<JavaSection>

First, download the [JDK](https://docs.oracle.com/en/java/javase/14/install/overview-jdk-installation.html#GUID-8677A77F-231A-40F7-98B9-1FD0B48C346A). Then, test that you can use the right commands.
 
On Windows, open `cmd` and type the following command into the prompt: 

```
java
```

If you get the below result, you may have to add the JDK to your [PATH](https://docs.oracle.com/en/java/javase/14/install/installation-jdk-microsoft-windows-platforms.html#GUID-A7E27B90-A28D-4237-9383-A58B416071CA) variable.

```
'java' is not recognized as an internal or external command,
operable program or batch file
```

Otherwise, you're probably good to go.

<IncompleteSection>

What do you have to do on Mac to get Java working the command line?

</IncompleteSection>

Running a Java file off of the command-line is relatively simple after the JDK is downloaded. 

Consider this code of `Main.java` and assume it is in a file on your computer:

```java
public class Main {
 public static void main(String[] args) {
  System.out.println("Hello World!");
 }
}
```

Use the `cd` command on your console to get to the directory that contains `Main.java`. Then, run the following command to compile the code:
```
javac Main.java
```
If it runs successfully, a file called `Main.class` will show up in the same directory, which can be executed with the next command:
```
java Main
```
If everything goes accordingly, the console should output `Hello World!`.

If you do USACO-style file I/O, meaning that files are in the "local directory", then the files must be located in the same directory as the source code (if you use the above method).

</JavaSection>

<PySection>

Download Python through [the official website](https://python.org). On Windows and Mac, you can download executable files directly; on Linux, you must either download the Python source code and compile from source, or obtain Python through your package manager.

Make sure that you are using the correct version of Python. Python 2 is quite different from Python 3 (but parts of the version number beyond 2. or 3. do not matter much). We generally recommend newcomers to use Python 3, but if you are used to programming in Python 2, that is OK too.

**The Python version can matter when using the command line to run Python;** sometimes, `python3` must be used instead of `python` in order to run Python 3. Try both commands, and pay attention to the version that Python prints, to determine if this is the case on your system. For example, running the following in Terminal on my computer produces:

```
python --version # prints Python 2.7.13
python3 --version # prints Python 3.8.1
```

</PySection>

</LanguageSection>

# Offline, Using an IDE

<Resources>
  <Resource source="IOI" title="2019 Contest Environment" url="https://ioi2019.az/en-content-26.html">software you can use at IOI</Resource>
</Resources>
<LanguageSection>

<CPPSection>

These often have C++ support already built-in.

<Resources>
  <Resource
    source="Microsoft" title="Visual Studio Code"
    url="https://code.visualstudio.com/"
    starred
  >
    More lightweight than Visual Studio, requires some configuration. See{' '}
    <a href="http://www.csc.kth.se/~jsannemo/slask/main.pdf">PAPC 2.1</a> for
    setup instructions.
  </Resource>
  <Resource source="Geany" title="Geany" url="https://www.geany.org/" starred>
    Lightweight, frequently used at IOI.
  </Resource>
  <Resource source="Code::Blocks" title="Code::Blocks" url="http://www.codeblocks.org/">
    Bad on Mac, <a href="https://codeforces.com/blog/entry/61780">apparently</a> unstable at IOI.
  </Resource>
  <Resource source="Apple" title="XCode" url="https://developer.apple.com/xcode/">
    Mac only.
  </Resource>
  <Resource source="Jetbrains" title="CLion" url="https://www.jetbrains.com/clion/">
    Requires a license, but{' '}
    <a href="https://www.jetbrains.com/community/education/#students">
      free for students
    </a>
    .
  </Resource>
</Resources>

<!--   <Resource source="Microsoft" title="Visual Studio" url="https://visualstudio.microsoft.com/vs/">
    Heavier cousin of VS Code. VS Code is better for competitive programming.
  </Resource> -->

</CPPSection>

<JavaSection>

It can be useful to use a Java IDE to take advantage of the powerful debugging features in Java.

<Resources>
  <Resource source="Jetbrains" title="IntelliJ IDEA" url="https://www.jetbrains.com/idea/">
    costs money but is{' '}
    <a href="https://www.jetbrains.com/community/education/#students">
      free for students
    </a>
    .
  </Resource>
  <Resource source="Eclipse" title="IDE" url="https://www.eclipse.org/eclipseide/">
    Freely available
  </Resource>
</Resources>

</JavaSection>

<PySection>

Python comes with a program, known as **IDLE** (Integrated Development and Learning Environment), that allows one to write and run Python code. It supports many features, such as syntax highlighting and automatic indentation, that one would normally expect from an IDE/text editor. However, feel free to use another editor or IDE if you want to.

</PySection>

</LanguageSection>