I have a project in code blocks that uses many different files - quite often written by other programmers. At the moment I have a situation in which I have two different sub-projects containing function named in the same manner. Let's say: F(int x). So F(int x) is defined in two source files in two different locations and they have two different headers. Also I have created two different namespaces for those headers:
namespace NS1
{
extern "C"{
#include "header1definingF.h"
}
}
namespace NS2
{
extern "C"{
#include "header2definingF.h"
}
}
But still compiler complains that it has multiple definition of F(int x). How can I workaround this in Code::Blocks (In Visual Studio it works just fine).
EDIT: To be more clear those headers include C code. I haven't thought it will be so messy. There are like thousands of source files using other projects including thousands of functions again... so what to do. I have absolutely no idea how to make it work.
I wonder why it works on Visual Studio, but not on Code Blocks. This suggests you do have an include guard.
Does this help?
Project->Build options...->Linker settings (tab)
-Wl,--allow-multiple-definition
I can't understand your problems clearly, but i think you should understand how the compiler works, when you use gcc to compel your program, your program first will be run include operator, that means if you include a header, the compiler will copy the header file to the file. if you include the header twice there will be a twice define error.so you must guarantee once,you can use
#ifndef __FILE_NAME__
#define __FILE_NAME__
// your code
#endif
If your problem is the redefine the function, you should know how the compiler distinguish the function, i think your problem is you do not use the namespace when you use the function.
The problem is that the namespace do not work for C functions (extern "C").
Here is a simple sample which do not compile:
namespace NS1
{
extern "C"{
int f()
{
return 1;
}
}
}
namespace NS2
{
extern "C"{
int f()
{
return 2;
}
}
}
In this case the two functions are different but have the same name: f(). If you just declare the functions, it will compile but they must refer to the same function.
This second sample works fine. The functions have the name NS1::f() and NS2::f() which are differents.
namespace NS1
{
int f()
{
return 1;
}
}
namespace NS2
{
int f()
{
return 2;
}
}
If you want to use two different c code, you can use objcopy which can help you to have a NS1_f() and NS2_f() function. After that you should rename all functions of the libraries in your includes. In this case, no namespace are used. This is normal, there is no namespace in C. Equivalent functions:
int NS1_f()
{
return 1;
}
int NS2_f()
{
return 2;
}
Short of editing the .cpp files themselves and renaming the functions (which is not a practical solution), your options are either making sure to only include one of the header files with duplicate functions at a time (which could be a huge maintainance problem) or, and this would be my recommendation, make use of namespaces. They will save you a ton of hassle in this situation.
You may need one of two things. The following is called a Header Guard:
#ifndef MYHEADER_H
#define MYHEADER_H
//your header code goes here
#endif
This way the header is only included once per object file that asks for it. However, if you want to have two methods with the same identifier, they have to be part of different Namespaces:
namespace myspace1{
void func(void);
};
namespace myspace2{
void func(void);
};
Other than that, there's not really much else you can do. You shouldn't have two functions with the same name in general. Also, you would have to modify this in the header files that you mentioned.
You are allowed to declare functions as often as you want, however they can only have ONE definition.
I believe you have to edit cpp files as well to nest the two functions into a corresponding namespace. Plus, you have to choose which function you want to call like namespace::function() or you can use using namespace with either of the namespaces you created. Hope this helps!
[Updates #1] It is easier to get confused between the declaration and definition of a function. Remember that you can redeclare non-member functions. Thus, if a header file only contains non-member function declarations, it is safe to include it multiple times in one translation unit (a cpp file). Adding ifndef/define in a header file is a good habit for avoiding potential problems but that is not what resolves your problem.
Your problem is that you want to have two different function definitions with the same function signature(its name and arguments) and that's not allowed in C++. You can either change one of their signatures or put them into a different namespace (which you are trying but without touching their definitions). Both ways require you to edit files containing their definitions.
[Updates #2]
As you updated the question with that the code is in C, I've searched and found this:
What should I do if two libraries provide a function with the same name generating a conflict?
it will surely help you to understand your problem more clearly and find a solution. Good luck!
Related
Well, I'm learning C++ and never really learned how to do stuff that is not OO.
I'm trying to get a bit more experience coding in C style.
GobalInformation.h
#pragma once
#ifndef GLOBALINFORMATION_H
#define GLOBALINFORMATION_H
#include "MapInformation.h"
namespace gi {
MapInformation mapInf;
};
#endif
I would like to be able to access gi::mapInf from every header and cpp in my project. Right now I'm including globalinformation.h in every header, so I'm getting linker errors with multiple definitions.
How can I work around the problem?
In header file only do
namespace gi {
extern MapInformation mapInf;
};
In CPP file provide the actual definition.
namespace gi {
MapInformation mapInf;
};
It will work as you intend.
If you are using the MapInformation across dynamic link library boundaries you might have to link against the library that includes the definition cpp file. Also on Window you might have to use dllimport/dllexport
Be aware that having globals in multiple compilation units can easily lead to order-of-initialization problems. You may wish to consider replacing each global with a function that returns a reference. In your case, put this in one cpp file and declare it in the header:
namespace gi {
MapInformation& getMapInf()
{
static MapInformation result;
return result;
}
}
Global variables are C, but namespaces are C++. There is a good discussion on using global variables and how they can be replaced by Singleton pattern: Globals and Singletons
And here is a simple sample: CPP/Classes/Singleton
Perhaps a better solution is to create a global object that contains all your global data. Then pass a smart pointer to the classes that actually need to access this shared global data.
Example:
class GlobalData
{
public:
int ticks_;
};
//Other file
class ThatNeedsGlobalData
{
public:
ThatNeedsGlobalData(std::shared_ptr<GlobalData> globalData);
};
This will save you some trouble.
Good luck!
Here are a few things that you need to take care of while trying to use global variables the way you have used.
Ensure that all the header files that the header files that GobalInformation.h includes are also enclosed insides #ifndefs. (I could not see mapinformation.h so I assume you have done it)
Just like CPP, C compiler also does not ensure order of the initialization of variables in different translation units(different C/CPP files).
Hence declare the header file as
//GlobalInformation.h
namespace gi {
extern MapInformation mapInf;
};
In a function that you know would be called first initialize the variable. This way lazy-initialization can also be acheived in C.
I have what seems a relatively simple question, but one that keeps defying my efforts to understand it.
I apologise if it is a simple question, but like many simple questions, I can't seem to find a solid explanation anywhere.
With the below code:
/*foo.c*/
#include "bar.h"
int main() {
return(my_function(1,2));
}
/*bar.h*/
int my_function(int,int);
/*bar.c*/
#include "bar.h" /*is this necessary!?*/
int my_function(int x, int y) {
return(x+y);
}
Simply, is the second inclusion necessary? I don't understand why I keep seeing headers included in both source files. Surely if the function is declared in "foo.c" by including "bar.h," it does not need to be declared a second time in another linked source file (especially the one which actually defines it)??? A friend tried to explain to me that it didn't really matter for functions, but it did for structs, something which still eludes me! Help!
Is it simply for clarity, so that programmers can see which functions are being used externally?
I just don't get it!
Thanks!
In this particular case, it's unnecessary for the reason you described. It might be useful in situations where you have a more complex set of functions that might all depend on each other. If you include the header at the top of the .cpp file, you have effectively forward-declared every single function and so you don't have to worry about making sure your function definitions are in a certain order.
I also find that it clearly shows that these function definitions correspond to those declarations. This makes it easier for the reader to find how translation units depend on each other. Of course, the names of the files might be sufficient, but some more complex projects do not have one-to-one relationship between .cpp files and .h files. Sometimes headers are broken up into multiple parts, or many implementation files will have their external functions declared in a single header (common for large modules).
Really, all inclusions are unnecessary. You can always, after all, just duplicate the declarations (or definitions, in the case of classes) across all of the files that require them. We use the preprocessor to simplify this task and reduce the amount of redundant code. It's easier to stick to a pattern of always including the corresponding header because it will always work, rather than have to check each file every time you edit them and determine if the inclusion is necessary or not.
The way the C language (and C++) is designed is that the compiler processes each .c file in isolation.
You typically launch your compiler (cl.exe or gcc, for example) for one of your c files, and this produces one object file (.o or .obj).
Once all your object files have been generated, you run the linker, passing it all the object files, and it will tie them together into an executable.
That's why every .c file needs to include the headers it depends on. When the compiler is processing it, it knows nothing about which other .c files you may have. All it knows is the contents of the .c file you point it to, as well as the headers it includes.
In your simplified example inclusion of "bar.h" in "bar.c" is not necessary. But in real world in most cases it would be. If you have a class declaration in "bar.h", and "bar.c" has functions of this class, the inclusion is needed. If you have any other declaration which is used in "bar.c" - being it a constant, enum, etc. - again include is needed. Because in real world it is nearly always needed, the easy rule is - include the header file in the corresponding source file always.
If the header only declares global functions, and the source file only implements them (without calling any of them) then it's not strictly necessary. But that's not usually the case; in a large program, you rarely want global functions.
If the header defines a class, then you'll need to include it in the source file in order to define member functions:
void Thing::function(int x) {
//^^^^^^^ needs class definition
}
If the header declares functions in a namespace, then it's a good idea to put the definitions outside the namespace:
void ns::function(int x) {
//^^^^ needs previous declaration
}
This will give a nice compile-time error if the parameter types don't match a previous declaration - for which you'd need to include the header. Defining the function inside its namespace
namespace ns {
void function(int x) {
// ...
}
}
will silently declare a new overload if you get the parameter types wrong.
Simple rule is this(Considering foo is a member function of some class):-
So, if some header file is declaring a function say:=
//foo.h
void foo (int x);
Compiler would need to see this declaration anywhere you have defined this function ( to make sure your definition is in line with declaration) and you are calling this function ( to make sure you have called the function with correct number and type of arguments).
That means you have to include foo.h everywhere you are making call to that function and where you are providing definition for that function.
Also if foo is a global function ( not inside any namespace ) then there is no need to include that foo.h in implementation file.
I'm learning C++ and I'm at a fairly low level still. - I'm currently looking at using header files and I have a two part question.
Part 1
As I understand them so far, header file definitions are similar to hard coded strings within VB.net? For example I can do the following #define STOCK_QUANTITY 300 and then reference my definition when using it within functions? I assume this works the same way as VB.net strings as I only need to change the value in one place should I need to make changes to the definition and my program references the number 300 on a few hundred different lines?
Part 2
Now, as I said I'm still learning so I'm still doing ye old multiplication tasks. I'm good within using functions with my main .cpp file but I'm not moving on to header files. This is my code snippet thus far.
add.h
#ifndef ADD_H
#define ADD_H
int add(int x, int y);
#endif
main.cpp
#include "stdafx.h"
#include <iostream>
#include "add.h"
int main()
{
using namespace std;
cout << add(3, 4) << endl;
return 0;
}
When trying to run this I receive 2 build errors and it will not compile.
Apologies is these are silly questions, but I would appreciate insight, tips or even some other things I should consider. Thanks.
EDIT
Based on an answer I've changed my add.h too
#ifndef ADD_H
#define ADD_H
int add(int x, int y)
{
return x + y;
}
#endif
As soon as I read the answer I realised I hadn't even told the function what to do :( - Gosh.
You have not added a function body for the function add
int add(int x, int y)
{
// add stuff here
}
This can be done in either the header file, or a seperate cpp file for add. You are trying to call the function that has no code. This is known as a function prototype.
You have only declared that the function add exists, which is why you can call it. But you don't actually define the function anywhere.
In C++ you have to differ between declaration and definition. Sometimes those are done at the same time, like when declaring a local variable. Other times you separate them, like when having a function prototype in a header file (like you do) then that's the declaration. The definition of the function is then the implementation of the function.
After the edit, you now have another problem. And that is if you include the header file in multiple source files, each of those source files (formally known as translation units) will have the function defined and you will get an error because of that.
It can be solved by making the function static or inline. Or better yet, create a new source file (like add.cpp) where you have the definition of the add function, and keep only the declaration (prototype) in the header file.
As for part 1 of your question:
While #defines do as you described, there are some of disadvantages with using them (e.g. They are parsed by the pre-processor, and not by the compiler so no type checking, and also you can get funky errors if you have slightly more complicated macros.
So while your statement is valid, in that it defines a global constant that you only need to modify in one place, and can use in multiple places, for that purpose it is better to have an actual constant variable in the header file:
e.g.
const int STOCK_QUANTITY = 300;
Now you explicitly name it an integer, and also the compiler can perform extra checking.
See also Item 3 in Effective C++ by Scott Meyer (which is a must read in my opinion if you are serious about contineouing programming in c++, although you need allready some experience before reading that.)
BRIEF: is it ever safe to do
namespace Foo {
#include "bar"
}
Before you blithely say no, I think I have some rules that allow it fairly safely.
But I don't like them, since they require the includer to separately include all global scope headers needed. Although this mightr be tolerable, if we imagine including within a namespace to be just a special management feature.
And overall, externs and forward declarations just don't work well from within namespaces.
So I gues I am asking
a) What other gotchas
b) is there a better way
== A [[Header-only library]] ==
I like writing libraries. [[Header-only libraries and linker libraries]].
E.g.
#include "Valid.hpp"
defines a template Valid, for a simple wrapper type.
(Don't get bogged down in "You should use some standard library for this rather than your own. This is an exanple. I dunno if Boost or C++ have yet standardized this. I have been using wrappers since templates were added to C++.)
Also, let us say, it is a header only library, that defines, in Valid.hpp,
a print function
std::string to_string( const Valid& v ) {
std::ostringstream oss;
if( v.valid() ) { oss << v; }
else { "invalid"; }
return oss.str();
}
And because I think it is the right thing to do,
I have Valid.hpp include the headers it depends on:
Valid.hpp:
#include <iostream>
#include <sstream>
template<typename T>
class Valid {
private:
T value_;
bool valid_
...
};
...
std::string to_string( const Valid<T>& v ) { ...
So far, so good.
I can use Valid straightforwardly.
== Name collision - trying to use include within namespace to work around ==
But sometimes there is a collision.
Sometimes somebody else has their own Valid.
Namespaces to the rescue, right? But I don't want to change all of my existing code to use the namespace.
So, I am tempted, in a new project that has a collision, to do
namespace AG {
namespace Wrapper {
#include "lib/AG/Wrapper/Valid.hpp"
}
}
AG::Wrapper::Valid<T> foo_v;
...
PROBLEM: the headers included are no longer freestanding. Everything defined inside is no placed inside
namespace AG::Wrapper.
It's not hard to "fix".
Al we "must" do is include all the top level libraries that Valid.hpp depends on.
If they have include guards, they will not be re-included.
#include <iostream>
#include <sstream>
namespace AG {
namespace Wrapper {
#include "lib/AG/Wrapper/Valid.hpp"
}
}
AG::Wrapper::Valid<T> foo_v;
...
But it is no longer freestanding. :-(
Worse, sometimes the header-only library contains extern declarations and forward declarations of stuff outside itself.
These declarations get placed inside the namespace too.
In particular, if the extern declarayion is inside a function defined in the namespace.
I.e. sometimes we use extern and forward declarations, rather than included an entire header file.
These get included in the namespace.
Q: is there a better way?
== :: doesn't do it ==
Hint: :: doesn't do it. At least not all the time, not in gcc 4.7.2.
(Gcc's behavior in this has changed over time. Gcc 4.1.2 behaved differently.)
E.g.
Type var;
namespace Foo {
void bar() {
extern ::Type ::var;;
extern ::Type ::Foo::bar;
extern ::Type::foo ::bar; // see the ambiguity?
};
But it's not just the ambiguity.
int var;
namespace Foo {
void bar() {
extern int var;
};
works - Foo::bar'svar is equal to ::var.
But it only works because of the declaration outside the namespace.
The following doesn't work
header
int var;
cpp
namespace Foo {
void bar() {
extern int var;
}
}
although the following does:
header
int var;
cpp
void bar() {
extern int var;
}
}
Basically, what this amounts to saying is that
it is not a trivial refactoring to put functions inside a namespace.
Wrapping a namespace around a chunk of code,
whether or not it is #include'd,
is not a sufficient.
... at least not if there are extern or forward declarations.
And even if you
== Opinion against putting includes within namespaces ==
Stackoverflow folks seem to be against putting #includes inside namespaces:
E.g. How to use class defined in a separate header within a namespace:
... you should never write a #include inside a namespace. Where "never" means, "unless you're doing something really obscure that I haven't thought of and that justifies it". You want to be able to look at a file, and see what the fully-qualified names are of all the things in it. You can't do that if someone comes along later and sticks an extra namespace on the front by including from inside their namespace. – Steve Jessop Jan 6 '12 at 16:38
Overall question:
Is there any way, from deep within a namespace,
to say "and now here are some names that I am depending on from the outside world, not within the namespace."?
I.e. I would like to be able to say
namespace A {
void foo() {
// --- here is a reference to gloal scope extreren ...
I know this is an old question, but I want to give a more detailed answer anyway. Also, give a real answer to the underlying problem.
Here's just a few things that can go wrong if you include a header from within a namespace.
The header includes other headers, which are then also included from within the namespace. Then a different place also wants to include these headers, but from outside the namespace. Because the headers have include guards, only one of the includes actually goes in effect, and the actual namespace of the stuff defined in the headers suddenly subtly depends on the order you include other headers.
The header, or any of its included headers, expects to be in the global namespace. For example, standard library headers will very often (in order to avoid conflicts) refer to other standard stuff (or implementation details) as ::std::other_stuff, i.e. expect std to be directly in the global namespace. If you include the header from within a namespace, that's no longer the case. The name lookup for this stuff will fail and the header will no longer compile. And it's not just standard headers; I'm sure there are some instances of this e.g. in the Boost headers too.
If you take care of the first problem by ensuring that all other headers are included first, and the second problem by making sure no fully qualified names are used, things can still go wrong. Some libraries require that other libraries specialize their stuff. For example, a library might want to specialize std::swap, std::hash or std::less for its own type. (You can overload std::swap instead, but you can't do that for std::hash and std::less.) The way to do this is close your library-specific namespace, open namespace std, and put the specialization there. Except if the header of the library is included in arbitrarily deeply nested namespaces, it cannot close those namespaces. The namespace std it attempts to open won't be ::std, but ::YourStuff::std, which probably doesn't contain any primary template to specialize, and even if it did, that would still be the wrong thing to do.
Finally, things in a namespace simply have different names than things outside. If your library isn't header-only but has a compiled part, the compiled part probably didn't nest everything in the namespace, so the stuff in the library has different names than the stuff you just included. In other words, your program will fail to link.
So in theory, you can design headers that work when included within a namespace, but they're annoying to use (have to bubble up all dependencies to the includer) and very restricted (can't use fully qualified names or specialize stuff in another library's namespace, must be header-only). So don't do it.
But you have an old library that doesn't use namespaces, and you want to update it to use them without breaking all your old code. Here's what you should do:
First, you add a subdirectory to your library's include directory. Call it "namespaced" or something like that. Next, move all the headers into that directory and wrap their contents in a namespace.
Then you add forwarding headers to the base directory. For each file in the library, you add a forwarder that looks like this:
#ifndef YOURLIB_LEGACY_THE_HEADER_H
#define YOURLIB_LEGACY_THE_HEADER_H
#include "namespaced/the_header.h"
using namespace yourlib;
#endif
Now the old code should just work the way it always did.
For new code, the trick is not to include "namespaced/the_header.h", but instead change the project settings so that the include directory points at the namespaced subdirectory instead of the library root. Then you can simply include "the_header.h" and get the namespaced version.
I don't think it's safe. You put all your includes into the namespace Foo...
Imagine some of your includes include something from the std namespace... I cannot imagine the mess !
I wouldn't do that.
Header files are not black boxes. You can always look at a header you're including in your project and see if it is safe to include it inside a namespace block. Or better yet, you can modify the header itself to add the namespace block. Even if the header is from a third-party library and changes in a subsequent release, the header you have in your project won't change.
I was once told in a programming class that C++ had achieved a better readability by letting the programmer declare its variable anywhere in a function block. This way, the variables were grouped together with the section of the code that dealt with it.
Why don’t we do the same for includes?
Put differently, why is it discouraged to put the include file next to the definition that will actually use it?
parser::parser()
{
// some initialization goes there which does not make use of regex
}
#include <boost/regex.hpp>
parser::start()
{
// here we need to use boost regex to parse the document
}
One of the reasons for this is that #include are context-less, they are just plain text inclusion, and having it in the middle of the code might have some unwanted effects. Consider for example that you had a namespace, and all your code in this file belongs to the namespace:
// Include on demand:
namespace ns {
void f() {} // does not need anything
//... lots of other lines of code
#include <vector>
void g() { std::vector<int> v; }
}
Now that might even compile fine... and wrong. because the inclusion is inside a namespace, the contents of the file are dumped inside ns and the included file declares/defines ::ns::std::vector. Because it is header only it might even compile fine, only to fail when you try to use that in an interface with a different subsystem (in a different namespace) -- This can be fixed, you only need to close all contexts, add the inclusion and reopen the same contexts...
There are other situations where the code in your translation unit might actually affect the includes. Consider, for example, that you added a using namespace directive in your translation unit. Any header included after that will have the using namespace directive in place, and that might also produce unwanted effects.
It could also be more error prone in different ways. Consider two headers that defined different overloads of f for int and double. You might add one (say the int version) towards the beginning of the file and use it, then add the other and use it. Now if you call f(5.0) above the line where the second header is included, the int version will be called --only overload available to the compiler at this point--, which would be a hard to catch error. The exact same line of code would have completely different meaning in different places in your file (admittedly that is already the case, but within the declarations in your file it is easier to find which is the one being picked up and why)
In general, the includes declare elements that you will be using in your component, and having them on the top provides a list of dependencies in a quick glance.
Imagine the following file:
#include <someheader>
namespace myns {
void foo() {
}
void bar() {
// call something from someheader:
func();
}
}
It might be tempting to put #include <someheader> nearer the point of usage. That would be fine iff you wrote the following instead:
namespace myns {
void foo() {
}
}
#include <someheader>
namespace myns {
void bar() {
// call something from someheader:
func();
}
}
The problem is in a medium/large sized file it's rather easy to loose track of quite how deeply nested you are inside namespaces (and other #ifdefs), depending on your indentation style. You might come back later and decide to move things around, or add another nested namespace.
So, if you write the #include at the top always you can never get bitten by accidentally writing something like:
namespace myns {
void foo() {
}
// Whoops, this shouldn't be inside myns at all!
#include <someheader>
void bar() {
// call something from someheader:
func();
}
}
which would be somewhere between wrong and very wrong depending on what exactly is in <someheader>. (You could for example end up with UB, by violating the ODR having multiple definitions which although otherwise legal and identical sequence of tokens match different functions and so violate § 3.2.5).
It's discouraged because most programmers are used to includes at the top of the file. Force of habit I think, and for consistency with 99% of existing code.
When I personally want to see what headers are included, I only look at the top. In special (and thankfully rare) cases where something is fishy, I might look for includes in the whole file.
To the compiler it makes no difference anyway.