tags:

views:

225

answers:

4

I have been trying to include a file in a included file e.g

main.cpp file

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

includedfile.cpp

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

this code does not work, the debuger says that name is not defined.

+8  A: 

You cannot have statements exist outside of a method!

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

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

string name = "jim";
Sander
A: 

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

Carl Seleborg
A: 

Changing includedfile.cpp to say

string name = "jim";

should work (confirmed by Comeau online). You should really also explicitly do

#include <string>

as otherwise you're relying on the fact that this is done by iostream.

tragomaskhalos
A: 

Well, of course it doesn't working because namespace defined works only in included.cpp. Simple solution here is to to write "using" once more in main. Many things in C\C++ defined at a "file scope" and when you are inserting one in another, it's not exactly clear how to define such scope.

Besides, it's indeed not good practice to include cpps. You should include h\hpp files (headers), because it makes troubles in growing projects (cohesion) and makes problems like 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();
bgee