Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does compiling an empty file follow the C++ standard?

Tags:

c++

There was an entry in the 1994 Obfuscated C contest that qualified as the smallest quine. It was just an empty file.

Is there something in the C++ spec that allows for compiling empty files? If not, what is the bare minimum for a "valid program?" I vaguely remember reading somewhere that there was a special case where an empty file is given a default implementation in the C++ spec, but I cannot find the reference.

I tried this, though I don't know that it is necessarily convincing.

$ rm main_empty.cpp
rm: cannot remove `main_empty.cpp': No such file or directory
$ touch main_empty.cpp
$ g++ -o empty main_empty.cpp
/usr/lib/gcc/.../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status

With a little coddling, you can get around the missing main.

$ g++ -Wl,--defsym=_start=_exit -Wl,--undefined=_exit \
    -nostartfiles -static -o empty main_empty.cpp

UPDATE:

It was noted that the main_empty.cpp was redundant. If you remove it from the command it compiles the same.

I added some static junk to the main_empty.cpp to see if it manifested in different behavior and it did not. It did change the executable size however.

#include <iostream>

struct Foo {
    Foo() {
        std::cout << "hi" << std::endl;
    }
} foo;

If you add a main to the file, and compile as normal it will output as you'd expect with typical static loading.

like image 248
Tom Kerr Avatar asked Jul 07 '13 19:07

Tom Kerr


1 Answers

C++ draft from 2012-11-02. 3.6.1:

A program shall contain a global function called main, which is the designated start of the program. It is implementation-defined whether a program in a freestanding environment is required to define a main function. [ Note: In a freestanding environment, start-up and termination is implementation-defined; start- up contains the execution of constructors for objects of namespace scope with static storage duration; termination contains the execution of destructors for objects with static storage duration. — end note ]

like image 146
CyberGuy Avatar answered Oct 15 '22 15:10

CyberGuy