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

    1 main 函数的概念

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

    2 main 函数的本质

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

    3 main 函数的参数

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

      int main()
      int main(int argc)
      int main(int argc,char* argv[])
      int main(int argc,char* argv[],char* env[])
      
      • argc :命令行参数个数
      • argv :命令行参数数组
      • env :环境变量数组
    • gcc 编译器的常见用法

      gcc a.c b.c c.c
      
      • argc :4
      • argv[0] :gcc
      • argv[1] :a.c
      • argv[2] :b.c
      • argv[3] :c.c
    • main 函数的参数示例

      • Demo

        #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 函数一定是程序执行的第一个函数么?

      • 看情况:如果使用了 gcc 编译器的属性关键字,那么可以指定在 main 函数之前执行一个函数
    • gcc 中的属性关键字

      • Demo

        #include <stdio.h>
        
        #ifndef __GNUC__
        #define __attribute__(x) 
        #endif
        
        //gcc属性关键字
        __attribute__((constructor))
        void before_main(){
            printf("%s
        ",__FUNCTION__);
        }
        
        __attribute__((destructor)) 
        void after_main(){
            printf("%s
        ",__FUNCTION__);
        }
        
        int main()
        {
            printf("%s
        ",__FUNCTION__);
            
            return 0;
        }
        
      • 编译

      • 运行

        before_main
        main
        after_main
        
  • 相关阅读:
    synchronized使用及java中的原子性问题
    Volatile 原理及使用,java并发中的可见性问题
    final 修饰符
    java 常见OPTS参数的含义
    Redis面试题
    Count(1),Count(*),Count(column)区别
    Mysql索引创建及删除
    springboot 非端口模式启动
    sql批量插入缓慢
    sql server sql语句导入数据到execl2007中
  • 原文地址:https://www.cnblogs.com/bky-hbq/p/13744672.html
Copyright © 2011-2022 走看看