问题记录
今天写了一段程序,如下:
#include <stdio.h>
int mian(int argc, char *argv[], char *envp[])
{
int ii = 0;
while (!envp[ii] != 0)
{
printf("%s\n", envp[ii]);
ii++;
}
return 0;
}
预期可以打印出编译时的环境变量等信息。
实际得到如下错误提示:
gcc book105.c
/usr/lib/gcc/x86_64-linux-gnu/7/…/…/…/x86_64-linux-gnu/Scrt1.o: In function_start': (.text+0x20): undefined reference to
main’
collect2: error: ld returned 1 exit status
原因分析
根据undefined reference to main
,程序里调用的三个参数main()
函数,没有在我的机器上实现。
我的机器: OS: Ubuntu 18.04.2 LTS on Windows 10 x86_64
尝试把程序扔到CentOS 7上
,可以正常运行。
解决
那么,ubuntu 1084
如何实现打印当前程序运行的环境参数。
#include <stdio.h>
extern char **environ;
int main(int argc, char *argv[])
{
int count = 0;
printf("\n");
while(environ[count] != NULL)
{
printf("[%s]::\n", environ[count++]);
}
return 0;
}
其他资料
GUN C文档
看GNU
官方文档:25.1 Program Arguments
这里面提到:
In ISO C you can define main either to take no arguments, or to take two arguments that represent the command line arguments to the program, like this:
int main (int argc, char *argv[])
In Unix systems you can define main a third way, using three arguments:
int main (int argc, char *argv[], char *envp[])
文档建议:
so to be portable it is best to write main to take two arguments, and use the value of environ.
C Primer Plus
见第六版,11.8章节:命令行参数。
C 编译器允许
main()
函数没有参数或者有两个参数(一些实现允许main()
有更多参数,属于对标准的扩展)。
关于environ
extern char **environ
extern
extern关键字先声明一下num变量,告诉编译器num这个变量是存在的,但是不是在这之前声明的,你到别的地方找找吧
StackOverflow:environ定义在哪里?
environ
is defined as a global variable in the Glibc source file posix/environ.c.
可以在线查看,也可下载glibc源码。
注意代码的说明:
/* This file just defines the
__environ' variable (and alias
environ’). */
glibc
只是定义了全局变量environ
, 是编译器拿来存放当前程序运行的环境参数的。