473,324 Members | 2,541 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

Using namespace across multiple files

4
The problem I have is basically the same as 'greentype' mentions at
<Link Removed>

I'm sharing variables through namespaces and a problem arises when I try to put my function definitions into a separate file.

Consider the following example, where I want to pass variable 'i', defined
in the main code, to the function a():

------------------------------
*** nn.h: ***
#ifndef _NN_H_
#define _NN_H_

namespace nn {
int i;
}
#endif

*** main.cpp ***
#include <iostream>
#include "nn.h"
using namespace std;
using namespace nn;

void a();

int main()
{
i=5;
a();
}

void a()
{
using namespace std;
using namespace nn;

i++;
cout << "i = " << i << endl;
}
------------------------------

But now if I put the definition of a() into a separate file ...

------------------------------
*** a.cpp ***
#include <iostream>
#include "nn.h"

void a()
{
using namespace std;
using namespace nn;

i++;
cout << "i = " << i << endl;
}
------------------------------

... then I get 'multiple definition' error when linking (g++ main.cpp
a.cpp -o main). If I make 'i' declaration in the header file 'extern' (as
suggested in other forums), I get 'undefined reference' error. I can compile when 'i' is declared as const in the header, but that's not what I want.

Any suggestions greatly appreciated.
Oct 2 '09 #1
9 12671
newb16
687 512MB
linker complains because 'i' is delared, but never defined.
Declare it with extern in header, and define it (without 'extern') only once in some .cpp file
Expand|Select|Wrap|Line Numbers
  1. // in some .cpp file
  2. namespace nn {
  3. int i;
  4. }
  5.  
Oct 2 '09 #2
Banfa
9,065 Expert Mod 8TB
This is nothing to do with namespaces. It is because you have declared i without the extern in the header file. The compiler treats this as a definition so the variable is defined in every source file you include the header in and you have multiple definitions of i.

By using the extern keyword

extern int i;

you are only declaring a, that is you inform the compiler that a variable a exists somewhere. You will then need to actually define a

int i;

in one of the source files.
Oct 2 '09 #3
weaknessforcats
9,208 Expert Mod 8TB
extern int i;

you are only declaring a, that is you inform the compiler that a variable a exists somewhere. You will then need to actually define a

int i;

in one of the source files.
Mostly correct.

Expand|Select|Wrap|Line Numbers
  1. extern int i;
declares that there is an int i with external linkage. It may be in this file or it may be in some other file.

For example, this is OK:
Expand|Select|Wrap|Line Numbers
  1. extern int i;
  2. int main()
  3. {
  4.     i = 10;
  5. }
  6. int i = 0;
Expand|Select|Wrap|Line Numbers
  1. extern int i = 0;
defines (creates) a variable int i with external linkage that has a value of 0. Other files can use this int i by coding extern int i.

When you place a value on your extern you actually create the variable. This is how you create sharable const values:

Expand|Select|Wrap|Line Numbers
  1. extern const int i = 10;
This creates a const int with a value of 10 that has external linkage. Other files can access this variable by coding:

Expand|Select|Wrap|Line Numbers
  1. extern const int i;
Oct 2 '09 #4
PetrH
4
Thank you guys for your replies, unfortunately none of that helps:

TO: newb16 & banfa: As I said, once I declare 'i' in the header as 'extern' and define it in main.cpp, a() in a.cpp doesn't know about it (undefined reference). And if I define 'i' in a() too, than I'm creating another variable, whereas I want to share (and change, if needed) the original one (defined in main.cpp).

TO: weaknessforcats: As I said, I don't want 'i' to be const. I want to be able to define it in main.cpp and share & change it (i++) in a.cpp. Which I can do as long as a() is in main.cpp, but not if I put it into a separate file, a.cpp.

Thanks,

Petr
Oct 2 '09 #5
PetrH
4
I see. Thank you guys. So if I understand this, the only way to get it to work is to make 'i' global, i.e. put the definition
'namespace nn { int i=5;}' in main.cpp, above int main() (and make the declaration 'extern', of course). But notice that in the original example (where function a() is in the SAME FILE as main()), 'i' was not global - I defined it within main(), yet still was able to share it with, and modify in, a() through the namespace. That is the framework I would like to retain, because I can't really make 'i' global, since it (and other variables I have and need to share) is CALCULATED in main() - I don't know their values in advance.

Petr
Oct 2 '09 #6
donbock
2,426 Expert 2GB
@PetrH
If you want the same variable i to be accessible from two or more source files then it either has to be a global variable or you need to pass a pointer-to-i to function a(). This is not a namespace issue.
Oct 2 '09 #7
Banfa
9,065 Expert Mod 8TB
@PetrH
You have your terminology wrong.

In your original example i was global, but because you only had 1 source file that wasn't obvious. Any variable defined at file scope without the static specifier has global linkage, this is how you defined i and this is what caused the initial problem when you put that definition into 2 source files (though inclusion).

You don't define i in main() in your original example. You assigned to it. You still can with the proposed solution.

I can't quite tell what it is that makes you think i can't be global since it is and has been throughout all code examples and suggested solutions in this thread.

Of course you should be avoiding use of global variables in C++ (and in C for that matter but it a little harder with C), they are very bad practice.
Oct 3 '09 #8
weaknessforcats
9,208 Expert Mod 8TB
I see. Thank you guys. So if I understand this, the only way to get it to work is to make 'i' global, i.e. put the definition
'namespace nn { int i=5;}' in main.cpp, above int main() (and make the
I'm sorry. I didn't understand that you are using namespaces.

When you use a namespace you have to understand that a namespace is not like a struct. That is, there is no single place you can go to see what's in the namespace. It's what they call an open-ended definition->Things are in the namespace if you say so.

In this case in a .cpp file, say Data.cpp put your namespace that defines the int:

Expand|Select|Wrap|Line Numbers
  1. Data.cpp
  2. namespace Stuff
  3. {
  4.     int i = 0;
  5. }
Then write a header file Data.h:

Expand|Select|Wrap|Line Numbers
  1. namespace Stuff
  2. {
  3.     extern int i;
  4. }
Then in main.cpp you can access the int:

Expand|Select|Wrap|Line Numbers
  1. #include <Stuff.h>
  2. int main()
  3. {
  4.     cout << Stuff::i;
  5. }
Of course this assumes that Data.cpp and main.cpp are both in your build.

If you read up on anonymous namespaces you will find out how to do away with the name Stuff altogether.
Oct 3 '09 #9
PetrH
4
Thank you guys. I get it now.
Oct 5 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Sean Dettrick | last post by:
I am wondering if it is possible to increment an integer at compile time using template<int N> (or by any other method, e.g. compiler directives etc), across multiple source files. This may...
12
by: Calum Grant | last post by:
In older C++ computer books, you'll often see using namespace std; even in my 1996 copy of Stroustrup. Nowadays, it seems to be considered better to qualify names to make it clearer what...
5
by: Brian Conway | last post by:
I am trying to use a variable from a login page web form (username) to build a select statement in another web form. How do I pass the variable from one form to the other and then insert that...
4
by: Jay | last post by:
Is it possible to split a class up in multiple files? if so how?
1
by: Paul Hodgson | last post by:
Is there any easy way to have .ascx controls used by pages in different virtual directories? My situation is that I have some pages that need to be accessed using SSL - so I've put these pages...
0
by: msustrick | last post by:
I'm working on a large asp.net maintenance application that has numerous utilities. There can be multiple files associated with a particular utility. The Namespace standard is...
1
by: ntocher | last post by:
Is it possible in a single query to search up to 12 tables for a similar text string and count the number each time a duplicate is found? I have a table for each month with a string field that...
2
by: vidhey | last post by:
Hi, here is my question. Can we use static variable across the multiple files? If so how?Please reply ASaP.
2
by: aruna.mysore | last post by:
Hi all, I have specific question about usage of extern. I want to share a single variable say int a; across multiple files. I would define it in file1.c as int a=0; int main() {
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.