zoukankan      html  css  js  c++  java
  • main函数与命令行参数

    main函数的概念

    • C语言中main函数称之为主函数
    • 一个c程序从main函数开始执行的

    下面的main函数定义正确吗?

    main函数的本质

    • main函数是操作系统调用的函数
    • 操作系统总是将main函数作为应用程序的开始
    • 操作系统将main函数的返回值作为程序的退出状态

    例子1:main函数的返回值
    test.c

    #include<stdio.h>
    int main()
    {
    	printf("hello world");
    	return 99;
    }
    

    gcc test.c -o test
    ./test
    echo $? --> 99

    test2.c

    #include<stdio.h>
    int main()
    {
    	printf("hello world2");
    	return 0;
    }
    

    gcc test2.c -o test2
    ./test && ./test2 --> hello world
    操作系统认为test不是正常退出,发生短路

    main函数的参数

    程序执行时可以向main函数传递参数

    例子2:main函数的参数

    #include <stdio.h>  
      
    int main(int argc, char* argv[], char* env[])  
    {  
        int i = 0;  
          
        printf("============== Begin argv ==============
    ");  
          
        for(i=0; i<argc; i++)  
        {  
            printf("%s
    ", argv[i]);  
        }  
          
        printf("============== End argv ==============
    ");  
          
        printf("
    ");  
        printf("
    ");  
        printf("
    ");  
          
        printf("============== Begin env ==============
    ");  
          
        for(i=0; env[i]!=NULL; i++)  
        {  
            printf("%s
    ", env[i]);  
        }  
          
        printf("============== End env ==============
    ");  
      
        return 0;  
    }  
    

    小技巧

    main函数一定是程序执行的第一个函数吗?

    例子2:gcc中的属性关键字

    #include <stdio.h>  
      
    #ifndef __GNUC__  
    #define __attribute__(x)   
    #endif  
      
    __attribute__((constructor))  
    void before_main()  
    {   
        printf("%s
    ",__FUNCTION__);  //gcc拓展宏代表函数名
    }  
      
    __attribute__((destructor))   
    void after_main()  
    {  
        printf("%s
    ",__FUNCTION__);  
    }  
      
    int main()  
    {  
        printf("%s
    ",__FUNCTION__);  
          
        return 0;  
    }  
    

    小结

    • 一个c程序从main函数开始执行
    • main函数是操作系统调用的函数
    • main函数有参数和返回值
    • 现代编译器支持在main函数前调用其他函数
  • 相关阅读:
    CODEVS 3137 栈练习1
    CODEVS 3138 栈练习2
    线段树———模板
    深度优先搜索与广度优先搜索———模板
    犯罪团伙 codevs 3554
    嘟!数字三角形 W WW WWW集合!
    寻找子串位置 codevs 1204
    流输入练习——寻找Sb.VI codevs 3096
    C++之路进阶——codevs3287(货车运输)
    c++之路进阶——codevs4543(普通平衡树)
  • 原文地址:https://www.cnblogs.com/yanyun888/p/9213202.html
Copyright © 2011-2022 走看看