C++使用fstream出现undefined reference错误

4

所以我需要在几分钟内快速编写代码来解决TSP问题,但是当我尝试读取文件时,我的编译器出现了错误。以下是示例代码,是什么导致了这个错误?

#include <cstdlib>
#include <iostream>
#include <fstream> 
using namespace std;

int tour_cost (int start, int end, int* array, int* tour) //calculate tour cost
{
    int cost = 0;
    for (int i = start; i < end; i++) 
        cost += array[tour[i] * tour[i] + tour[i + 1]];
    return cost;
}

int main()   
{
    int array [625];
    int tour [25];
    int dist = 0;   
    ifstream infile ("cities.txt");
    for (int i = 0; i < 25; i++) {
        for (int j = 0; j < 25; j++ ) {
            infile >> dist;
            array[i*i + j] = dist;
        }
        tour[i] = i;
    }
    cout << tour_cost (0,24,array,tour);
    return 0;
}

样本错误:

ps2.cpp:(.text+0xc0): undefined reference to `std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(char const*, std::_Ios_Openmode)'
ps2.cpp:(.text+0xe8): undefined reference to `std::istream::operator>>(int&)'

4
你是如何编译它的?我使用默认设置编译时一切正常。 - John Odom
1个回答

6

在编译C++代码时,必须使用g++而不是gcc。


哎呀,我以为我疯了。 - ptgrimes
这不会导致这些错误,不是吗?它不会理解C++语法。这是链接器的问题... 对吗? - Mooing Duck
@MooingDuck:如果我理解正确,编译器确实是相同的,而链接阶段是特定于C++的。 - 6502

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接