Reputation:

Problem when including a file with an included file

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.

Upvotes: 0

Views: 306

Answers (4)

bgee
bgee

Reputation: 989

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();

Upvotes: 0

tragomaskhalos
tragomaskhalos

Reputation: 2753

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.

Upvotes: 0

Carl Seleborg
Carl Seleborg

Reputation: 13295

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?

Upvotes: 0

Sander
Sander

Reputation: 26344

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";

Upvotes: 8

Related Questions