C ++中的错误未定义对main的引用

时间:2016-04-26 18:41:09

标签: c++ linux unix

我一直在说错误......

(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status
make: *** [FuelGauge] Error 1

我的项目以及我的代码和makefile。此外,如果您发现任何其他编码错误,请随意指出它们=]

enter image description here

模拟器类

 #include <iostream>
 #include <iomanip>
 #include "FuelGauge.h"
 #include "Odometer.h"

 using namespace std;

 int main(){
    FuelGauge fuel(0); return 0; 
 }

FuelGauge类

#include "FuelGauge.h"
#include <iostream>
#include <cstdlib>

using namespace std;
void FuelGauge::incrementGas(int gas){
    if(currentFuel < maxGallon) {
        currentFuel++;
    }
}
int FuelGauge::getGas(){
    return currentFuel;
}

FuelGauge.h

class FuelGauge {

private: 
            int currentFuel;
            int maxGallon;

public:
            void incrementGas(int);
            int getGas();           
};

里程表类

#include "FuelGauge.h"
#include "Odometer.h"
#include <iostream>
#include <cstdlib>
using namespace std;

private: int currentMileage;
Odometer::Odometer(){
    mileage = 0;
    Fuelgauge g;
}

int Odometer::getMileage(){
    return mileage;
}

void Odometer::incrementMileage(){
    if(mileage <= 999999){
    mileage++;
}
else{
    mileage = 0;
}

void Odometer::decreaseMileage(){

    if(g.currentFuel > 24){
        g.currentFuel--;
    }
 }
}

Odometer.h

class Odometer{

private:
    int mileage;
    int gallons;
}

生成文件

FLAGS = -Wall
CC = g++
SYMBOLS = -g

all: FuelGauge Odometer CarSimulatorDemo

FuelGauge: FuelGauge.cpp FuelGauge.h
    $(CC) $(FLAGS) $(SYMBOLS) -o $@ FuelGauge.cpp
Odometer: Odometer.cpp Odometer.h
    $(CC) $(FLAGS) $(SYMBOLS) -o $@ Odometer.cpp    
CarSimulatorDemo: CarSimulatorDemo.cpp
    $(CC) $(FLAGS) $(SYMBOLS) -o $@ CarSimulatorDemocpp
clean:
    rm FuelGauge Odometer CarSimulatorDemo

2 个答案:

答案 0 :(得分:1)

您遇到的问题可能不是因为您的c ++代码而是您的Makefile。您希望将每个cpp文件编译为一个对象文件而不是单独的应用程序,然后将它们链接到一个应用程序中。要将cpp编译为.o文件,请使用-c选项。

总结你的Makefile应该如下:

FLAGS = -Wall
CC = g++
SYMBOLS = -g

all: app

app: FuelGauge.o Odometer.o CarSimulatorDemo.o
    $(CC) $(FLAGS) $(SYMBOLS) *.o -o app
FuelGauge.o: FuelGauge.cpp FuelGauge.h
    $(CC) $(FLAGS) $(SYMBOLS) -c -o FuelGauge.o FuelGauge.cpp
Odometer.o: Odometer.cpp Odometer.h
    $(CC) $(FLAGS) $(SYMBOLS) -c -o Odometer.o Odometer.cpp    
CarSimulatorDemo.o: CarSimulatorDemo.cpp
    $(CC) $(FLAGS) $(SYMBOLS) -c -o CarSimulatorDemo.o CarSimulatorDemo.cpp
clean:
    rm FuelGauge.o Odometer.o CarSimulatorDemo.o app

记住将Makefile中的空格更改为制表符!

PS。 #ifndef应始终暗示使用#endif并在标头文件中始终使用它们!

答案 1 :(得分:0)

您的Odometer.h不会以#endif结尾。由于它已经通过FuelGauge.h包含,因此ODOMETER_H被定义,并且#ifndef之后的所有内容都没有被编译(预处理器将它扩展为空格)。包括函数main