-1

I am trying to define a function searchview::run() in a source file ("searchview.cpp"), after it has been declared in my header file ("searchview.h"). When I do this, I am getting an error code saying that there are multiple definitions of searchview::run(), and it is first defined on line 5. Both error codes point to line 5, and it is defined only in the source file and declared only in the header file.

searchview.h

using namespace std;

class Searchview {
public:
    void run();
};

And searchview.cpp

#include "searchview.h"

using namespace std;

void Searchview::run() {
    while(!search_results.empty()) {
        cout << "No results found" << endl;
    }
}
Ben M
  • 1
  • 3
    Did you - by any chance - put `#include "xxx.cpp"` somewhere? – IWonderWhatThisAPIDoes Apr 27 '21 at 19:10
  • [using namespace std is bad practice](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) and is especially bad in a header file. You're pulling everything from the standard namespace into the global namespace for *everyone* who includes your file whether they like it or not! And your header file doesn't even use anything from std! – Kevin Apr 27 '21 at 19:31
  • 1
    The error cannot be duplicated with just the posted code. See [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). then [edit](https://stackoverflow.com/posts/67289241/edit) the question and add the actual code that triggers the error. – dxiv Apr 27 '21 at 21:04
  • I am running into the same problem. If I comment out every piece of code in the project except for these two files, it still gets the same error, but if I copy and paste the same code into a new project, it runs without a problem. Should i just scrap this file and make a new .h file? – Ben M Apr 27 '21 at 21:13
  • @BenM Then it sounds like a problem with the build files - makefiles, project files etc. That's not a C++ language question, and cannot be answered without a lot more details about your particular environment. – dxiv Apr 28 '21 at 02:04
  • I made a new project, brought all the files into it and created a new .h file, and it runs without issue. Thanks all for the help – Ben M Apr 28 '21 at 12:48

1 Answers1

0

One issue is that your searchview.h is missing include guards. For example:

#ifndef SEARCHVIEW_H
#define SEARCHVIEW_H

// header body here

#endif

or:

#pragma once

// header body here
0x5453
  • 12,753
  • 1
  • 32
  • 61
  • Apologies, but I did include both the include guards, did not include them when pasting into stack overflow. Additionally, I have not called "searchview.cpp" anywhere else. – Ben M Apr 27 '21 at 20:21