【发布时间】:2021-03-18 16:30:36
【问题描述】:
添加 .h 文件后,我在编译程序时遇到了一些问题。
我得到的错误如下所示。
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/Scrt1.o: in function `_start':
(.text+0x24): undefined reference to `main'
collect2: error: ld returned 1 exit status
我尝试将 int main() 添加到 minesClass.cpp,但没有解决问题
程序包含三个文件:main.cpp、minesClass.h、minesClass.cpp
main.cpp
#include "minesClass.h"
#include <iostream>
#include <time.h>
#ifndef MINESBOARD_H__
#define MINESBOARD_H__
int main()
{
MinesweeperBoard board(10, 10, GameMode::NORMAL);
board.getMines();
board.debug_display();
}
#endif
minesClass.cpp
#include "minesClass.h"
#define MINESBOARD_H__
#ifndef MINESBOARD_H__
MinesweeperBoard::MinesweeperBoard(int width, int height, GameMode mode)
{
for (int column = 0; column < height; column++)
{
for (int row = 0; row < width; row++)
{
board[column][row].hasFlag = false;
board[column][row].isRevealed = false;
}
}
}
void MinesweeperBoard::getMines(GameMode mode)
{
srand(time(NULL));
switch (mode)
{
case 1:
EASY;
for (int column = 0; column < height; column++)
{
for (int row = 0; row < width; row++)
{
int minePropability = RAND_MAX * 0.1;
int num = rand();
if (num <= minePropability)
{
board[column][row].hasMine = 1;
}
else
board[column][row].hasMine = 0;
}
}
break;
case 2:
NORMAL;
for (int column = 0; column < height; column++)
{
for (int row = 0; row < width; row++)
{
int minePropability = RAND_MAX * 0.2;
int num = rand();
if (num <= minePropability)
{
board[column][row].hasMine = 1;
}
else
board[column][row].hasMine = 0;
}
}
break;
case 3:
HARD;
for (int column = 0; column < height; column++)
{
for (int row = 0; row < width; row++)
{
int minePropability = RAND_MAX * 0.3;
int num = rand();
if (num <= minePropability)
{
board[column][row].hasMine = 1;
}
else
board[column][row].hasMine = 0;
}
}
break;
case 4:
DEBUG;
break;
default:
break;
}
}
void MinesweeperBoard::debug_display() const
{
for (int column = 0; column < height; column++)
{
for (int row = 0; row < width; row++)
{
std::cout << "[";
if (board[column][row].hasMine)
std::cout << "M";
else
std::cout << ".";
if (board[column][row].isRevealed)
std::cout << "o";
else
std::cout << ".";
if (board[column][row].hasFlag)
std::cout << "f";
else
std::cout << ".";
std::cout << "]";
}
std::cout << width<<height<<std::endl;
}
}
#endif
minesClass.h
#include <iostream>
#define MINESBOARD_H__
#ifndef MINESBOARD_H__
enum GameMode
{
DEBUG,
EASY,
NORMAL,
HARD
};
struct Field
{
bool hasMine;
bool hasFlag;
bool isRevealed;
};
class MinesweeperBoard
{
Field board[100][100];
int width;
int height;
public:
MinesweeperBoard(int width, int height, GameMode mode);
void debug_display() const;
void getMines(GameMode mode);
};
#endif
我查看过类似的问题,即“未定义对 `main 的引用”,但其中大多数是基于缺少 int main()。
【问题讨论】:
-
你能发布你的构建设置吗?
-
去掉 .cpp 文件中的包含保护。
-
在 cpp 文件中包含警卫是奇怪的。
-
不幸的是,该程序必须基于我的教师格式,她对这些警卫非常务实,所以他们是必要的
-
永远不要在 .cpp 文件中放置标头保护。
标签: c++ visual-studio-code windows-subsystem-for-linux