Error in C++ class implementation

Asked

Viewed 48 times

-2

I’ve been trying to solve a mistake since yesterday, but so far I don’t know what I’m doing wrong when implementing a C class++.

I put the class with the prototypes in an extension file . h (header) and the methods in one of the same name only of extension . cpp, I did the simplest possible to know where the error is but so far I could not solve:

test. h

#ifndef TESTE_H
#define TESTE_H


class Teste {
    public:
        void mostra();
};


#endif

cpp testing.

#include "teste.h"
#include <iostream>


void Teste::mostra() {
    std::cout << "Isso é um Teste\n";
}

main.cpp (I think the mistake is not here, but I put it just to be sure)

#include "teste.h"


int main() {
    Teste *test = new Teste;
    test->mostra();
    
    
    return 0;
}

Error:

undefined reference to `Teste::mostra()'
clang-5.0: error: linker command failed with exit code 1 (use -v to see invocation)
  • 1

    It worked here: https://replit.com/@acwoss/Differentleandeskscan#main.cpp

  • 2

    The problem is not the code, it is the way you are compiling and generating the executable. The code of the.cpp test module is not being linked in the final executable. Add the commands you are using to compile to the question, to give a final answer.

1 answer

-1

See this execution in a folder only with those files you listed, on Windows

C: Teste> >cl /EHsc main.cpp teste.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30037 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

main.cpp
teste.cpp
Generating Code...
Microsoft (R) Incremental Linker Version 14.29.30037.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:main.exe
main.obj
teste.obj

C: Teste> >main
Isso e um Teste

C: Teste> >dir
 O volume na unidade C não tem nome.
 O Número de Série do Volume é 7E52-1BF2

 Pasta de C: Teste> 

16/07/2021  01:07    <DIR>          .
16/07/2021  01:07    <DIR>          ..
16/07/2021  01:03               109 main.cpp
16/07/2021  01:08           175.104 main.exe
16/07/2021  01:08               755 main.obj
16/07/2021  01:03               107 Teste.cpp
16/07/2021  01:03                96 Teste.h
16/07/2021  01:08            64.041 teste.obj
               6 arquivo(s)        240.212 bytes

I don’t know what environment you’re using this in but for example using gcc on linux can run g++ -o tst main.cpp teste.cpp and the compiler will create the executable tst. See above that in Windows created main.exe.

If you are using an IDE each IDE has its own way of doing these things, but in general just create a project, insert main.cpp and create the class Teste.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.