-3

I getting a undefined reference error when I try compile the code. I only just be be to test the Grafo class fuctions

grafo.h:

#ifndef GRAFO_H
#define GRAFO_H

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>


/*  Classe Grafo - Matriz de adjecencia  */
class Grafo
{
    public:
        //  Atributos
        int num_vertices;
        int *vertices; 
        int **arestas;
        char tipo;

        //  assinaturas dos metodos
        Grafo(int nv,char t);
        void printGrafo();

};
#endif

grafo.cpp

#include "grafo.h"

Grafo::Grafo(int nv,char t);  
Grafo::void printGrafo();

Grafo::Grafo(int nv,char t){
    num_vertices = nv;
    vertices = new int[num_vertices];
    tipo = t;

    //criar matriz
    arestas = new int *[num_vertices];
    for(int i = 0; i < num_vertices;i++){ arestas[i] = new int[num_vertices];}

    // inicializar valores da matriz
    for(int i = 0; i < num_vertices;i++){
        vertices[i] = 0;
        for(int j = 0; j < num_vertices;j++){
            arestas[i][j] = 0;
        }
    }

}

void Grafo::printGrafo(){
    std::cout << " | ";
    for(int i = 0; i < num_vertices;i++){
        std::cout << i << " ";
    }
    std::cout << std::endl;
        for(int i = -3; i < num_vertices;i++){
        std::cout << "_";
    }
    std::cout << std::endl;
    for(int i = 0; i < num_vertices;i++){
        std::cout << i << " | ";
        for(int j = 0; j < num_vertices;j++){
            std::cout << arestas[i][j] << " ";
        }
        std::cout << std::endl;
    }
}

main.cpp

#include "grafo.h"

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>

int main(){
  Grafo G = Grafo(5,'D');
  G.printGrafo();
}

when I try compile with command g++ main.cpp -o main.exe. I recive the following error msg:

/tmp/ccPxPLjS.o: In function main': main.cpp:(.text+0x29): undefined reference toGrafo::Grafo(int, char)' main.cpp:(.text+0x35): undefined reference to `Grafo::printGrafo()' collect2: error: ld returned 1 exit status

Someone may help-me with this job? >.<

1 Answers1

2

First of all remove first lines from Grafo.cpp file:

Grafo::Grafo(int nv,char t);  
Grafo::void printGrafo();

These are causing errors in compilation (GCC):

grafo.cpp:3:27: error: declaration of 'Grafo::Grafo(int, char)' outside of class is not definition [-fpermissive]
 Grafo::Grafo(int nv,char t);
                           ^
grafo.cpp:4:8: error: expected unqualified-id before 'void'
 Grafo::void printGrafo();
        ^~~~

Then include all source files into compilation invocation:

g++ -o test test.cpp grafo.cpp

This will cause sources to compile properly, if done like this:

g++ -o test test.cpp

it will cause similar errors as described in your question:

ccVmPgnr.o:test.cpp:(.text+0x20): undefined reference to `Grafo::Grafo(int, char)'
ccVmPgnr.o:test.cpp:(.text+0x2c): undefined reference to `Grafo::printGrafo()'
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Diodacus
  • 663
  • 3
  • 8