C/C++ on Windows without Visual Studio

Someone interested in programming recently asked me about the easiest way to program in C/C++ on Windows without using bloated Microsoft stuff, so I wrote down some simple instructions on how to use MSYS2 with GCC and MinGW. I figured I’d share those instructions here, in case someone else finds them useful.

MSYS2 is kind of like a small operating system with its own package manager that lets build native Windows applications using Unix tools. It’s possible you’ve even heard of its package manager pacman before, since it’s also used in Arch Linux.

So, first things first, go download and install MSYS2.

After that’s done, open the MSYS2 UCRT64 prompt from the Start Menu.

Upgrade packages.

pacman -Syu

Install required packages for compiling C

pacman -S gcc mingw-w64-ucrt-x86_64-gcc make cmake ninja 

Open a C file

nano test.c

Paste this in (copy with CTRL-C, paste with middle mouse click)

#include <stdio.h>
#include <windows.h>
#include <winuser.h>

int main(int argc, char const *argv[]) {
	MessageBoxA(NULL, "aaa", "bbb", MB_OK);
	printf("ccc\n");
	return 0;
}

Press CTRL-X to save, Y and ENTER to confirm, then compile with

gcc test.c -luser32 -o test.exe

(-luser32 means you’re linking the code with user32 library that contains the code for MessageBoxA. If you didn’t do that, the compilation would have failed because the linker wasn’t able to find the MessageBoxA function.)

Now you can run it with

./test.exe

You should have seen a popup with an OK button, and then also ‘ccc’ in the terminal.

There you go, you’ve successfully compiled a C program without Visual Studio.

Of course, you don’t have to use a terminal editor, and you also don’t need to have your files within the MSYS environment. Let’s say you have a project at C:\Users\yourname\project. You can navigate to that directory with cd /c/Users/yourname/project and then proceed to compile with gcc again.

It’s also helpful to use a script for the compile command so you don’t need to type it out every time. You can just put the command from earlier into a build.sh like this

echo "gcc test.c -luser32 -o test.exe" > build.sh
chmod +x build.sh

and then just build with

./build.sh

For bigger projects you mind want to consider something like Makefiles or CMake, but you can get pretty far with just a simple script like the one above.

A super simple Makefile could look like this

test.exe: test.c
	gcc $^ -luser32 -o $@

To build using the Makefile, you just run make.