gpt4 book ai didi

c++ - 为什么我得到 "undefined reference to main"

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:55:21 26 4
gpt4 key购买 nike

我是编程的新手,有一个非常基本的问题可能会在其他线程中得到解答,但我认为它们太高级了,我无法理解如何回答。到目前为止,我实际上已经在此站点上找到了很多答案,但这是第一个迫使我创建帐户并询问的问题。 无论如何,我正在 linux mint 18.3 上运行一个非常基本的示例程序。现在我已经看到这个确切的代码在装有 Windows 8 的机器上工作,我相信所以我想知道这是否可能是问题所在。我创建了一个类,当我插入我的对象然后构建并运行时,我得到:

/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o||在函数 _start':|
(.text+0x20)|| undefined reference
main'|

这是完整的代码:

#include <iostream>
#include "Gladius.h"
using namespace std;

int main()
{
Gladius io;
return 0;
}

这是非常基本的。这是.h

#ifndef GLADIUS_H
#define GLADIUS_H


class Gladius
{
public:
Gladius();

};

#endif // GLADIUS_H

和类的 .cpp。

#include "Gladius.h"
#include <iostream>

using namespace std;
Gladius::Gladius()
{
cout << "The Gladius is a short sword" << endl;
}

我知道这看起来非常简单,但我只是在学习编码,我一直在寻找为什么这不起作用的解释,但我看到它在另一台电脑上完全按原样工作。无论如何,我们将不胜感激。

这是我在命令行中找到的内容,如果这回答了您关于 cmd 中的内容的问题。

g++ -Wall -fexceptions -g -std=c++11 -Wall -I -c/home/gator/Documents/Spartan1/Gladius.cpp -o obj/Debug/Gladius.o/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:在函数 _start' 中:
(.text+0x20): 对
main' 的 undefined reference collect2:错误:ld 返回 1 退出状态

最佳答案

了解编译器选项(gcc/g++ 编译器):

  • -c : 编译和汇编,但不链接
  • -o file : 将输出放入file

所以当你运行的时候

g++ filename.cpp -o executable_name

,您生成一个可以执行的应用程序。

问题是当您尝试编译“Gladius.cpp”并且编译器正在尝试搜索 main() 定义时,您正在编译、汇编和链接。

所以在你的情况下,编译步骤是:

首先编译“Gladius.cpp”并生成目标文件“Gladius.o”:

g++ -Wall -fexceptions -g -std=c++11 -c Gladius.cpp

接下来编译“main.cpp”并生成目标文件“main.o”:

g++ -Wall -fexceptions -g -std=c++11 -c main.cpp

通过链接“main.o”和“Gladius.o”生成可执行文件

 g++ -Wall -fexceptions -g -std=c++11 -o main main.o Gladius.o

现在你可以运行“main”了:

./main

关于c++ - 为什么我得到 "undefined reference to main",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48940315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com