• 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函数前调用其他函数
  • 相关阅读:
    js中调用ocx控件
    web.xml配置文件中<async-supported>true</async-supported>报错的解决方案
    shiro整合spring配置
    shiro中的reaml理解及实现机制
    oracle数据库安装
    关于身份认证、角色认证和权限认证的shiro-web例子
    创建maven管理的web项目
    hadoop Hive 的建表 和导入导出及索引视图
    hadoop Mapreduce组件介绍
    hadoop hive组件介绍及常用cli命令
  • 原文地址:https://www.cnblogs.com/yanyun888/p/9213202.html
Copyright © 2020-2023  润新知