gcc compiles with the error cc: Internal error: Killed (program cc1). This is basically due to insufficient memory. This can be solved by temporarily modifying the swap partition.

1. swap What swap partitions do

When a Linux system runs out of physical memory, a portion of the physical memory can be freed for use by currently running programs. The freed space may come from programs that have not operated for a long time, and the freed space is temporarily saved in SWAP space, and then restored from SWAP to memory when those programs want to run. In this way, the system always swaps when there is not enough physical memory. This is what swap partitions do.

Under what circumstances will the system use SWAP?

Actually, it does not wait for all physical memory to be consumed before using the space for swap, when it is used is controlled by the swappiness parameter value:

cat /proc/sys/vm/swappiness

The default value is 60.

  • swappiness=0 indicates maximum use of physical memory before swap space.
  • swappiness=100 means that swap partitions are used aggressively and data from memory is moved to swap space in a timely manner.

2. Creating a swap swap partition

Refer to the following commands:

1
2
3
4
5
6
7
8
9
# Create a swap partition
# The 64M and 16 here can be adjusted to multiply by the overall swap size (1024M). You can run dd --help to see detailed help information.
sudo dd if=/dev/zero of=/swapfile bs=64M count=16
# Set permissions so that only root users have access
sudo chmod 600 /swapfile
# Mark swapfile files as swap space
sudo mkswap /swapfile
# Enable swap files
sudo swapon /swapfile

View information about the swap partition:

1
2
3
4
5
6
# Verify, view swap partition
sudo swapon --show
# View the capacity of a swap partition file
ls -lh /swapfile
# View the active swap
free -h

3. Deleting the swap partition

If you are only using the swap partition for temporary expansion so that programs such as gcc can be compiled, you can remove the swap partition after the compilation is complete by executing the following command:

1
2
sudo swapoff /swapfile
sudo rm /swapfile

4. Persistent swap files

The swap file is commonly enabled with the above command. However, if the system is rebooted the server will not retain the swap settings. This can be changed by adding the swap file to /etc/fstab.

Back up the /etc/fstab file first:

1
sudo cp /etc/fstab /etc/fstab.bak

Execute the following command to add the swap file information to the end of the /etc/fstab file.

1
2
<br />echo "/swapfile  swap  swap    defaults 0 0" >> /etc/fstab
# echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab