1

I'm having an issue where I am trying to use variables stored in a struct called from a header file. I am able to call to each cpp file ie., call an action from one to another however variables are proving difficult.

Client.cpp

#include <iostream>
#include "Header.h"
#include <vector>;
#include <conio.h>;
#include <string>;

using namespace std;

int main()
{
    cout << "Please enter a name: " << flush;
    cin >> sNam.sNames;

    main2();

    return 0;
}

Admin.cpp

#include <iostream>
#include "Header.h"
#include <vector>;
#include <conio.h>;
#include <string>;

using namespace std;

void main2()
{
    if (sNam.sNames == sNam1.sNames1)
    {
        cout << "Correct Entry...\n";
    }
    else if (sNam.sNames != sNam1.sNames1)
    {
        cout << "Incorrect Entry...\n";
    }

}

Header.h

#pragma once
#include "Admin.cpp"
#include "Client.cpp"

struct Names
{
    string sNames;
    string sNames1 = "John";

}sNam, sNam1;
user4581301
  • 33,082
  • 7
  • 33
  • 54
Calmtb2019
  • 29
  • 1
  • 1
    Don't include *.cpp files. The header doesn't even need to know about those files. It's a one way street where the *.cpp files need to know about the header and [amost never] vice versa. I would also choose a better name than `main2()` for the function you call. Something actually descriptive. – sweenish Aug 23 '21 at 17:37
  • 1
    cpp files include header files not the other way around. So client.cpp and admin.cpp are correct. Remove the .cpp includes from header.h and you should be fine – Pepijn Kramer Aug 23 '21 at 17:39
  • Note: Once you stop including the cpp file, you'll have a problem with multiple definitions as Header.h fully defines variables and both cpp files include the header. See [When to use extern in C++](https://stackoverflow.com/questions/10422034/when-to-use-extern-in-c) for details and a solution. – user4581301 Aug 23 '21 at 18:09
  • Minor point: `std::cout` and `std::cin` are tied together, so you don't need to flush `std::cout` after a prompt. Reading from `std::cin` will flush `std::cout`. – Pete Becker Aug 23 '21 at 18:12

1 Answers1

0

don't include cpp files
also sNam and sNam1 are defined in both cpp files, you will have link time error
include Header.h in both Client.cpp and Admin.cpp
then declare what's common in Header.h

#pragma once
// #include "Admin.cpp"
// #include "Client.cpp"

struct Names
{
    string sNames;
    string sNames1 = "John";
};

extern Names sNam, sNam1;

void main2();

in one of cpp files

#include "Header.h"

Names sNam, sNam1;
Errorist
  • 224
  • 2
  • 6