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 ==============\n");  
      
    for(i=0; i<argc; i++)  
    {  
        printf("%s\n", argv[i]);  
    }  
      
    printf("============== End argv ==============\n");  
      
    printf("\n");  
    printf("\n");  
    printf("\n");  
      
    printf("============== Begin env ==============\n");  
      
    for(i=0; env[i]!=NULL; i++)  
    {  
        printf("%s\n", env[i]);  
    }  
      
    printf("============== End env ==============\n");  
  
    return 0;  
}  

小技巧

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

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

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

小结

  • 一个c程序从main函数开始执行
  • main函数是操作系统调用的函数
  • main函数有参数和返回值
  • 现代编译器支持在main函数前调用其他函数

猜你喜欢

转载自www.cnblogs.com/yanyun888/p/9213202.html