(.text+0x20): undefined reference to `main‘ 问题

在这里插入图片描述

问题记录

今天写了一段程序,如下:

#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, 是编译器拿来存放当前程序运行的环境参数的。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值