c++ - 编译空文件是否遵循 C++ 标准?

标签 c++

1994 Obfuscated C contest 中有一个条目有资格作为最小的quine。这只是一个空文件。

C++ 规范中是否有允许编译空文件的内容?如果不是,“有效程序”的最低限度是多少?我依稀记得在某处读到过,在 C++ 规范中有一个空文件被赋予默认实现的特殊情况,但我找不到引用。

我试过了,虽然我不知道它是否一定有说服力。

$ 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

稍加呵护,您就可以绕过丢失的主电源。

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

更新:

注意到 main_empty.cpp 是多余的。如果您从命令中删除它,它会编译相同的内容。

我在 main_empty.cpp 中添加了一些静态垃圾,看看它是否表现出不同的行为,但事实并非如此。但是它确实改变了可执行文件的大小。

#include <iostream>

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

如果您将 main 添加到文件中,并正常编译,它将按照您对典型静态加载的预期输出。

最佳答案

2012 年 11 月 2 日的 C++ 草案。 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 ]

关于c++ - 编译空文件是否遵循 C++ 标准?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17515790/

相关文章:

DataGridView DefaultCellStyle 的 C++/CLI 填充

c++ - 在排序链表中添加节点

c++ - 有没有一种方法可以显式销毁给定 boost::asio::io_context 上挂起的所有处理程序?

c++ - opencv:如何在方向图像上绘制箭头

c++ - 错误 : wrong number of template arguments (0, 应该是 1)

c++ - 如何在将 CMake 用于 LLVM 时启用共享库构建?

C++ 错误 : expected unqualified-id before '[' token

c++ - 将电影转换为 OpenNI *.oni 视频

c++ - 从另一个线程终止一个线程(被卡住)

c++ - 库无法链接特定体系结构的可能原因?