سؤال

I'm learning data structures right now, and I've been trying to figure out this error for over an hour!

In my main, I call:

...
#include "Graph.hpp"
    Graph* g  = new Graph();
    g->addVertex("vertex1");
...

and in my Graph.cpp I have:

...
#include "Graph.hpp"
    Vertex * Graph::addVertex( string name ) {
    ...
    }
...

In my Graph.hpp:

...
class Graph{
    Vertex *addVertex(string);
...
}

I'm getting the error when I compile:

undefined reference to `Graph::addVertex(std::string)'

EDIT:

The makefile:

CC=g++
CXXFLAGS = -std=c++11 -O2 -g - Wall
LDFLAGS= -g

main: main.o
    g++ -o main main.o

main.o: Edge.hpp Graph.hpp Vertex.hpp Graph.cpp
هل كانت مفيدة؟

المحلول

Answer : Here :

main: main.o
    g++ -o main main.o

Your executable, main, is not linked with the Graph.o file, thus generating an undefined reference.


Solution :

Here is a simple Makefile that you won't have to modify every time you want to add a new .cpp file to your project :

EXE := a.out # nexecutable name

SRC := $(wildcard *.cpp) # get a list of all the .cpp in the current directory

OBJ := $(SRC:.cpp=.o) # compile every .cpp file into a .o file

CXXFLAGS = -W -Wall -std=c++11 -O2

$(EXE): $(OBJ)
    $(CXX) $(OBJ) -o $(EXE) # $(CXX) contains g++ by default

If you want your Makefile to react to header files modifications too :

EXE := a.out # executable name

SRC := $(wildcard *.cpp) # get a list of all the .cpp in the current directory

OBJ := $(SRC:.cpp=.o) # compile every .cpp file into a .o file

DEP := $(OBJ:.o=.d) # from every .o file create a .d file that will keep track of header files

CXXFLAGS = -W -Wall -std=c++11 -O2
CPPFLAGS = -MMD -MP # let g++ handles the header files dependencies for you

-include $(DEP) # includes the .d files into the Makefile

$(EXE): $(OBJ)
    $(CXX) $(OBJ) -o $(EXE) # $(CXX) contains g++ by default

نصائح أخرى

You have a missing semicolon on the end of your class definition. This will cause whatever comes next to be treated as a variable declaration of that class type, not whatever it was supposed to be. In such cases, later references to "what it was supposed to be" typically fail as well.

Always start with the first compiler error encountered. Error lists in IDEs often confuse the order, I suggest looking at the actual compiler output.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top