【问题标题】:Why can't the linker find main()?为什么链接器找不到 main()?
【发布时间】:2012-11-25 04:18:26
【问题描述】:

我收到下一条错误消息:

usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o: In
function `_start':  (.text+0x20): undefined reference to `main' 
collect2: ld returned 1 exit status

我唯一的代码是:

FILE *f = fopen("data/file.dat", "rb");
fseek(f, 0, SEEK_END);
long pos = ftell(f);
fseek(f, 0, SEEK_SET);

char *bytes = malloc(pos);
fread(bytes, pos, 1, f);
fclose(f);

现在,我来自 Java 背景,但我一直在谷歌搜索,它说我可能缺少参考但我不知道它可能是什么,我什至添加了 #include <stdio.h> 并阅读了一些关于添加一个extern,但我不知道在哪里,因为我没有其他文件,除非我需要参考 .dat 文件?

编辑我也尝试过强制转换字节数组(char*)malloc(pos);,但它也没有帮助。

编辑 2 整个代码使用的是 NS-3 框架,但在我添加这些行之前,一切都编译得很好。它看起来像这样:

#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/mobility-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("ThirdScriptExample");

int 
main (int argc, char *argv[])
{
      .....
//STARTS FILE READING
  FILE *f = fopen("data/Terse_Jurassic_10_14_18.dat", "rb");
  fseek(f, 0, SEEK_END);
  long pos = ftell(f);
  fseek(f, 0, SEEK_SET);

  char *bytes = (char*)malloc(pos);
  fread(bytes, pos, 1, f);
  fclose(f);

  Simulator::Stop (Seconds (10.0));

  pointToPoint.EnablePcapAll ("third");
  phy.EnablePcap ("third", apDevices.Get (0));
  csma.EnablePcap ("third", csmaDevices.Get (0), true);

  Simulator::Run ();
  Simulator::Destroy ();
  return 0;
}

编译器错误信息是:

[1888/1930] cxxprogram:  -> build/scratch/data/data
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o: In
function `_start': (.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status Build failed  -> task in 'data'
failed (exit status 1):   {task 43470800: cxxprogram  -> data}

我非常确定 NS-3 代码(由于代码行而我没有添加的部分和读取文件后的部分都可以正常工作,因为在添加部分以读取文件之前一切正常。

【问题讨论】:

  • 您的代码是否在 int main () {...} 函数中?
  • 您的代码中有main 吗?类似int main()int main(int argc, char **argv) 或类似的东西。你可以编译没有main 的程序,但你不能link 它。
  • 是的int main (int argc, char *argv[]){}
  • 向我们展示所有代码 - 并向我们展示编译语句(例如gcc -Wall foo.c -o foo)。
  • 是和上面的代码在同一个文件还是在不同的文件?

标签: c++ linker-errors ld


【解决方案1】:

我唯一的代码是

您没有将此代码放入main 函数(您必须拥有),或者您的编译器/链接器调用不正确。鉴于您提供的详细信息,无法确定是哪个。

另外,您的问题标题不正确:您在读取文件时没有问题,您在链接您的程序(打算读取文件)时遇到问题。

【讨论】:

  • 对不起标题我真的不知道我必须在 C 中这样做。除此之外我确实有一个主要的 =/
【解决方案2】:

你的程序必须包含一个main()函数。

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
    FILE *f = fopen("data/file.dat", "rb");
    fseek(f, 0, SEEK_END);
    long pos = ftell(f);
    fseek(f, 0, SEEK_SET);

    char *bytes = malloc(pos);
    fread(bytes, pos, 1, f);
    fclose(f);
    free(bytes);
    return 0;
}

【讨论】:

  • 我已经有 main 但它仍然无法工作 =/ 即使返回 0;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多