Home > Enterprise >  Cannot include .cpp and .h files in Visual Studio 2022
Cannot include .cpp and .h files in Visual Studio 2022

Time:11-27

I have created a class Dialog and separated it into .cpp (Dialog.cpp) and .h (Dialog.h). My cpp file looks like this:

#include "Dialog.h"
#include <iostream>
using namespace std;

namespace Model1
{
    void Dialog::initialize ()
    {
          cout << "initialization";
    }
}

And here is my h file:

using namespace std;
class Dialog
    {
        public:
            void initialize ();
    };

When I debug the code in visual studio 2022 I get this:

cannot open source file "Dialog.h"
name followed by '::' must be a class or namespace name
Cannot open include file: 'Dialog.h': No such file or directory ConsoleApplication1 
symbol cannot be defined within namespace 'Model1'  ConsoleApplication1

When I changed my header file to

using namespace std;
namespace Model1 {
    class Dialog
    {
    public:
        void initialize();
    };
}

And now I have these errors:

cannot open source file "Dialog.h"
name followed by '::' must be a class or namespace name
Cannot open include file: 'Dialog.h': No such file or directory 

How can I fix the problem?

CodePudding user response:

The problem is that in the header file you've defined class Dialog in global namespace while you're trying to define the member function Dialog::initialize() in Model1 namespace.

This will not work because the out-of-class definition for the member function of a class must be in the same namespace in which the containing class is.

Thus, to solve this you can either define the class(in the header) in namespace Model1 or implement the member function(in the source file) in global namespace. Both these methods are shown below:

Method 1

Here we define the class in namespace Model1 in the header and leave the source file unchanged.

dialog.h

namespace Model1   //added this namepspace here
{
class Dialog
    {
        public:
            void initialize ();
    };
}

Working demo 1


Method 2

Here we define the member function in global namespace in source file and leave the header file unchanged.

dialog.cpp

#include "Dialog.h"
void Dialog::initialize ()
{
      cout << "initialization";
}

Working demo 2

  • Related