Problem when including file with included file

I am trying to include a file in an included file like

main.cpp file

#include <includedfile.cpp>
int main(){
     cout<<name<<endl;
}

      

includedfile.cpp

#include <iostream>
using namespace std;
string name;
name = "jim";

      

this code doesn't work, debuger says name is undefined.

0


source to share


4 answers


You shouldn't have statements outside of the method!

name = "jim"; // This is outside of any method, so it is an error.

      



You can refactor your code so that the variable declaration is also an initial assignment, which should be valid (my C ++ is a little rusty, so I might be wrong at this point).

string name = "jim";

      

+8


source


However, you must have a good reason to include the .cpp file. It happens, but it's rare! What exactly are you trying to achieve? Or are you just experimenting?



0


source


Change includefile.cpp to say

string name = "jim";

      

should work (verified by Como online). You should really also explicitly do

#include <string>

      

because otherwise you are relying on iostream doing it.

0


source


Well of course it doesn't work because the namespace mentioned only works in include.cpp. The simple solution is to write "use" again in the main. A lot of things in C \ C ++ are defined in "file scopes", and when you nest them inside each other, it's not really clear how to define such a scope.

Also, it's not really a good practice to include cpps. You should include h \ hpp files (headers) because this creates problems in growing projects (cohesion) and creates problems as discussed here.

#include <includedfile.h>
#include <iostream>
int main()
{     
    std::cout << name << endl;
}

//includedfile.cpp
void DoSomething()
{
  std::string name;
  name = "jim";
}

//includedfile.h
void DoSomething();

      

0


source







All Articles