Home  >  Article  >  Database  >  关于main()函数的小技巧

关于main()函数的小技巧

WBOY
WBOYOriginal
2016-06-07 15:36:101738browse

话说,有这样一道据说是月薪2W的笔试题: #include stdio.h void print() { * } void main() { } 要求在*部分写代码使整个程序运行后输出“hello world”,有些人说,这还不简单啊,于是写出这样的代码: 01. #include stdio.h 02. void print() 03. { 04. p

   话说,有这样一道据说是月薪2W的笔试题:

#include "stdio.h"
void print()
{
*
}
void main()
{
}

        要求在*部分写代码使整个程序运行后输出“hello world”,有些人说,这还不简单啊,于是写出这样的代码:

01.#include "stdio.h"

02.void print()

03.{

04.    printf("hello world");

05.}

06.void main()

07.{

08.    print();

09.}

        这样写的确是没问题,但是违背了题目的要求,因为题目不允许修改main函数,这下仿佛我们就没辙了,因为我们学习C/C++语言的时候,明确说明main函数是程序的主函数,也是程序的入口函数,可是现在主函数为空,那怎么会执行子函数呢?

        其实这个笔试题考察的不是我们对基本知识的理解,而是要学会发现问题解决问题的能力,有时候,当一条路走不通的时候,我们就要换一条路,通过查找资料,我们发现其实C++是可以修改入口函数的。

        这里需要一个C++预编译标识符 #pragma comment()   来帮助我们搞定这个问题。他的使用类型是:pragma comment( comment-type ,["commentstring"] )。

        comment-type是一个预定义的标识符,指定注释的类型,应该是compiler,exestr,lib,linker之一。

        commentstring是一个提供为comment-type提供附加信息的字符串。

        这里我们需要使用linker来修改链接设置:

#pragma comment(linker, "/entry:print")

        看到了么?通过/entry参数来设置程序链接时候的主函数为print,这样,就相当于print函数是整个程序的主函数,他替换了main函数的作用,相反的,main函数则成为了一个子函数

        完整的代码和运行结果如图所示:

        至于#pragma comment(lib, "msvcrt.lib")是因为使用了puts函数,如果使用printf的话可以不要这一句

 关于main()函数的小技巧

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:??数据库Next article:程序员:提高编程效率的技巧