Build a self replicating program (quine)

Understand what a quine is and how you can build your own.

Build a self replicating program (quine)
Photo by Tine Ivanič / Unsplash
A simple introduction to the world of computer viruses

The rules are simple, build a program that outputs its source code. Opening and reading the source file is considered cheating. More precisely, a quine receiving any kind of input is considered invalid.

The Kleene’s theorem

This exercise is a direct application of the Kleene’s theorem. But the theorem was created long before computers. Here is how I understand it.

First form — The fixed-point theorem

It says that for every conditional program e, there is a program true for ϕe(x) = f(e,x) for any input x. e is the program logic, and ϕe its syntax. It means that there is one program which execution will result in its source code.

Second form

From this we can deduct its second form, which states that for every conditional program, there is one program which execution will result in the same program.

Let’s build one

Let’s build your first simple quine. You have to print the source code of your program without opening it, use at least 2 comments and two functions. A diff <(./quine) quine.c should return nothing.

Solution in C

#include <stdio.h>

/*
   Hey, this is an outside comment
*/

char *get_str()
{
	return "#include <stdio.h>%1$c%1$c/*%1$c   Hey, this is an outside comment%1$c*/%1$c%1$cchar *get_str()%1$c{%1$c%2$creturn %3$c%4$s%3$c;%1$c}%1$c%1$cint main(void)%1$c{%1$c%2$c/*%1$c%2$c   Hey, this is an inside comment%1$c%2$c*/%1$c%2$cchar *str = get_str();%1$c%2$cprintf(str, 10, 9, 34, str);%1$c}%1$c";
}

int main(void)
{
	/*
	   Hey, this is an inside comment
	*/
	char *str = get_str();
	printf(str, 10, 9, 34, str);

Good to know

This type of programs was named Quine in honor of the philosopher Willard Van Orman Quine, who worked on the subject of indirect self-reference.

Want more ?

I worked on many of these exercices during my journey at the 42 Paris School. If you like these challenges, try implementing the other quines available on my repository 😊

GitHub - jterrazz/42-dr-quine: 🔃 This project addresses auto-replication issues, and confronts you the Kleene’s recursion theorem. A medium article is available in description.
🔃 This project addresses auto-replication issues, and confronts you the Kleene&#39;s recursion theorem. A medium article is available in description. - GitHub - jterrazz/42-dr-quine: 🔃 This project…

I’m starting a new website called myopen.market. It’s still in a early stage, but if you found this article useful, subscribing to its newletters would be the best way to encourage me ❤️

My Open Market
A plateform for connecting shops and customers using ethereum smart contracts. myopen.market