Interfacing with third-party public libraries/codes - c++

I would like to evaluate an algorithm with an available public code in my project. I have integrated the files the algorithm needs into my project: kodtree.h, kodtree.cpp, pinpolyhedron.h, and pinpolyhedron.cpp. However, the compiler complains about the ambiguous symbols. I changed the variable names which were ambiguous to something else and the compiler compiles it with no problem. This way does not look like an elegant way of fixing the issue.
I was thinking of using namespace but found out that, for example, the file kodtree.h has several externs.
Would putting them into namespaces cause me trouble since they can contain extern?
Could someone kindly let me know the things I should be aware of when creating namespaces for such libraries?
Is using namespace the right way of doing this?
Or is it better to create an interface class for this library and put everything, i.e., kodtree.h, kodtree.cpp, pinpolyhedron.h, and pinpolyhedron.cpp, inside that class and make them private?
What is the recommended way of doing this?
I would appreciate any tips.

Is using namespace the right way of doing this?
Yes, but not the way you try to go about it. Libraries should properly namespace themselves, but sometimes they can't or won't for various reasons. It's best to leave them be, unless you intend to write a full blown wrapper around the library code.
We can always apply a little discipline and namespace our own code. Simply put, we can do something like this in every one of our own source files1:
#include <some_library.h>
#include <my_other_project_header.h>
namespace ProjectName { namespace ModuleName {
// Your code here
}}
That way your code is nicely insulated from whatever you include. And barring any extern "C" things, there should be no conflicts. Whatever the library header drags in, it will not cause clashes with code you write inside your namespaces. All the while, your code can refer to project entities with at most one level of qualification (code in Module1 can refer to Module2::Foo, or to Module1::Bar as simply Bar). Beyond that you can always refer to things outside your Project namespace by fully qualifying things or by employing using declarations.
1: If your compiler supports C++17, it can be the more palatable:
namespace ProjectName::ModuleName {
}

Related

When to use "::" for global scope in C++?

Every once in a while, I stumble across some code that I'm maintaining that challenges the way I think about my code style. Today was one of those days...
I'm aware that about why you would want to use the scope operator to define global scope. In fact, here scope resolution operator without a scope is a great link tell you why.
However, I saw something that made me think today. All the classes in question were wrapped into a namespace for the project (good!), but I did see copious usage of the global scope operator. Namely, it was used for everything from C libraries (with the exception of uint8_t and the like... yes, the programmer used the .h version of this library since apparently the version of g++ they were running still threw warnings about the new C++ standard). Is this useful? I view this as just as a waste of characters (reminds me of using the this pointer... except in the case of the copy constructor and assignment operator where it helps in clarifying which object is which). Am I missing something? Sure, someone can come around and name something along the lines of usleep() or stderr (where I saw the most usage of "::"), but won't they know that doing so will probably break something horribly? At what point do you say "screw it" in terms of the scope operator and just tell yourself that someone who names a function a certain way within your namespace is asking for trouble?
So my question is... what is the "correct" (subjective I understand) way of using the global scope operator in this context? Should everything not included in std or your own namespaces have the global scope explicitly defined? I tend to err on the side of caution and use "std::" to avoid the using directive, but is anything gained from using the global scope operator here? I tend to think for clarity's sake it does lend to the fact that we aren't getting the variable or function in question from the current namespace, but I'm torn between including it and not given today's developments.
As always, thanks for the help and guidance as I look to make my code cleaner, more readable, and (of course) significantly more awesome.
I use it quite infrequently; only when some ambiguity needs resolving for whatever reason. This is pretty subjective, though.
There may be some occasions (say, inside a template) where you're worried about ADL causing ambiguities only in certain cases:
template <typename T>
void foo(T t)
{
::bar(t); // :: just in case there's a `bar` in `T`'s namespace
}
There is almost no correct answer to this as it's almost totally style related, with the exception that if you think you may want to change from where you are going to import some declaration(s)/definition(s), in which case, when you use them, you don't specify any scope and import them using the using directive (to import a subset from the namespace) or the using namespace directive to import the entire set from the namespace.
Mostly the using directive is used as a convenience directive, but it is a powerful way to direct which declarations/definitions are used. My preference is to not specify the scope and import the declarations. Doing this allows for easy changes if ever they are needed while reducing visual noise. Also, specifying the scope would mean I'd be "locked in" from where I am getting the declarations (well, I'd have to do a global search and replace to change it).
If ever there is a conflict (you try an use a declared item with the same name that has been imported from more than one namespace) the compiler will let you know, so there's no real danger.
Readable code is that has the least amount of noise. namespace prefixes normally provide nothing but noise. So baseline is to not have them at all.
Namespaces were introduced to C++ mainly to handle 3rd party stuff out of one's control. To allow libraries drop prefixing, while clients can use terse names by applying using.
Just because you can have the same name in many namespaces does not imply it is a good idea to too. If a project uses some environment, platform API, library set, whatever that puts name in global, those names are better be avoided for other purposes. As with or without prefixes they will bear mental overhead.
Use of :: is rare in well-shaped code, and frequent uses appear in wrapper classes for that same functionality.
Consider the following cases.
Public library.
You are writing an exportable library with public headers. And you absolutely have no clue in what environment your headers will be included. For example, someone may do:
namespace std = my_space::std;
#include "your_header"
And all your definitions will be corrupted, if you simply use: std::list<int>, etc. So, it's a good practice to prepend :: to everything global. This way you can be absolutely sure what you're using. Of course, you can do using (in C++11) or typedef - but it's a wrong way to go in headers.
Collaborative .cc/.cpp files.
Inside your own code that is not exposed to public in any way, but still editable not only by you - it's a good practice to announce, what you're going to use from outside of your namespace. Say, your project allows to use a number of vectors - not only an std::vector. Then, where it's appropriate, you put a using directive:
// some includes
using vector = ::std::vector<int>; // C++11
typedef ::std::vector<int> vector; // C++03
namespace my_namespace {
...
} // namespace my_namespace
It may be put after all includes, or inside specific functions. It's not only gives control over the code, but also makes it readable and shortens expressions.
Another common case - is a mixing of global C functions and a C++ code. It's not a good idea to do any typedefs with function names. In this situation you should prepend C functions with the global scope resolution operator :: - to avoid compilation problems, when someone implements a function with a same signature in the same namespace.
Don't use :: for relative types and namespaces - or you'll lose the benefit of using namespaces at all.
Your own code.
Do what you want and how you want. There is only one good way - the way you fill comfortable with your own code. Really, don't bother about global scope resolution in this situation, if it's not requiered to resolve an ambiguity.

Using fully qualified names in C++

I am a C++ newcomer, trying to learn the language in parallel as I work on a project that requires it. I am using a fairly popular and stable open source library to do a lot of heavy lifting. Reading through the source, tutorials and code samples for the library, I have noticed that they always use fully qualified names when declaring types, which often results in very long and verbose lines with lots of ::'s. Is this considered best practice in C++? Is there a different way to deal with this?
They may have found it easier than answering lots of questions from people who tried the example code and found it didn't work, just because they didn't "use" the namespaces involved.
Practices vary - if you're working on a large project with lots of diverse libraries and name clashes, you may wish to proactively use more namespace qualifiers consistently so that as you add new code you won't have to go and make old code more explicit about what it's trying to use.
Stylistically, some people prefer knowing exactly what's being referred to to potentially having to dig around or follow an IDE "go to declaration" feature (if available), while other people like concision and to see fuller namespace qualification only on the "exceptional" references to namespaces that haven't been included - a more contextual perspective.
It's also normal to avoid having "using namespace xxx;" in a header file, as client code including that header won't be able to turn it off, and the contents of that namespace will be permanently dumped into their default "search space". So, if you're looking at code in a header that's one reason they might be more explicit. Contrasting with that, you can having "using namespace" inside a scope such as a function body - even in a header - and it won't affect other code. It's more normal to use an namespace from within an implementation file that you expect to be the final file in a translation unit, compiling up to a library or object that you'll link into the final executable, or perhaps a translation unit that itself creates the executable.
First typedefs:
typedef std::vector<MyTypeWithLongName>::const_iterator MyTypeIt;
//use MyTypeIt from now on
Second "using"
using std::string;
//use string instead of std::string from now on
Third "using namespace"
using namespace std;
//Use all things from std-namespace without std:: in front (string, vector, sort etc.)
For the best practice: Don't use 'using' and 'using namespace' a lot. When you have to use it (sometimes keeps the code cleaner) never put it in the header but in the .cpp file.
I tend to use one of those above if the names get really long or I have to use the types a lot in the same file.
If you are writing your own libraries you will certainly have heavy use of namespaces, In your core application there should be fewer uses. As for doing something like std::string instead of starting with using namespace std; imo the first version is better because It is more descriptive and less prone to errors

Is using namespace..like bad? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why is 'using namespace std;' considered a bad practice in C++?
Every time I use using namespace std I always get that "thats a terrible programming habit".
Now I'm graduating this December with my B.S. in C.S. but I don't claim to know everything, but no one has ever explained why this is so bad. I understand what it does but I honestly don't see a huge deal with it.
Anyone care to explain? In my mind it just makes typing cout a whole lot more bearable than std::cout.
I can understand why you wouldn't want to put it in a header file, but just in a normal implementation file... I dont see why it would be a problem.
There is no problem using using namespace std in your source file when you make heavy use of the stl and know for sure that nothing will collide.
However, very often you don't need to use using namespace std or not in the entire file:
Did you know you can:
void somefunction()
{
// Use it in a particular scope
using namespace std;
cout << "test" << endl;
}
found this useful post elsewhere:
Namespaces separate and organize functionality. You can have a xander333::sort() function and it won't conflict with std::sort() or boost::sort() or any other sort(). Without namespaces there can be only one sort().
Now let's say you've put "using namespace std;" in all your source files and you've implemented a simple templated function called fill() in the global namespace of one of your files. This file also depends on a header from libFoo -- foo.hpp. Version 2.1 of libFoo comes out and all of a sudden your program no longer compiles. You version of fill() suddenly conflicts with another fill()! What happened?
It turns out that the folks implementing libFoo included in the new version of foo.hpp when they didn't before. Now you have all of the standard algorithms being included in your source file, and your using namespace std; has pulled them all into the global namespace. std::fill() now directly conflicts with your fill().
More insidious, you've gotten your code to compile by renaming your fill() to xander333_fill(), but something's not working right -- your report numbers are off. It turns out that your custom divides() function, which does fixed precision math, is no longer being called because the templated function from (also newly included by foo.hpp) makes for a better match because you're calling types did not exactly match the declared types.
Thread with relevant discussion is here:
http://www.cplusplus.com/forum/unices/27805/
a "good practice" that I am aware of is not to put using namespace in include files, but be free to use it to your taste in your private .cpp files. I know people who like everything to be fully qualified, and some (like me) who assume that string is an std::string unless stated otherwise.
The reason for this is that if/when others use your include file (and this happens always), they are forced to accept your programming style.
Good luck!
My preference is to:
never put a using directive in a header file (the things that include your header may not like the fact that you forced them to have the using directive).
always do things like using std::cout; at the top of the implementation files so I don't have to do std::cout everywhere in my code.
It's primarily about good housekeeping. If you're not really going to use more than a few identifiers in a namespace, why clutter up your own namespace by dumping all of the identifiers from that namespace into yours? It's preferable to use using std::cout. However, if you use a namespace very heavily and it doesn't cause any collisions, go ahead and use using namespace.
Another reason to not use using other than avoiding potential naming collisions is to speed up your IDE and possibly compiles.
If you're using Visual Studio, using namespace std and/or using namespace boost can kill intellisense entirely. There are a lot of symbols in these namespaces that you may not realize and dumping them into the global namespace can be ludicrous.
Avoiding using statements for entire namespaces helps prevent unintentional conflicts between libraries. Supposed you made your own class that had the same name as something in std, then unless you explicitly use std:: you will have name conflicts.
It's probably best to try to avoid conflicts like this in the first place, but if you specify the namespace for each member in your code it will be less ambiguous.
If you get tired of typing std::cout all the time, you can use a using statement for just that member.

Does using a C++ namespace increase coupling?

I understand that a C++ library should use a namespace to avoid name collisions, but since I already have to:
#include the correct header (or forward declare the classes I intend to use)
Use those classes by name
Don't these two parameters infer the same information conveyed by a namespace. Using a namespace now introduces a third parameter - the fully qualified name. If the implementation of the library changes, there are now three potential things I need to change. Is this not, by definition an increase in coupling between the library code and my code?
For example, look at Xerces-C: It defines a pure-virtual interface called Parser within the namespace XERCES_CPP_NAMESPACE. I can make use of the Parser interface in my code by including the appropriate header file and then either importing the namespace using namespace XERCES_CPP_NAMESPACE or prefacing declarations/definitions with XERCES_CPP_NAMESPACE::.
As the code evolves, perhaps there is a need to drop Xerces in favour of a different parser. I'm partially "protected" from the change in the library implementation by the pure-virtual interface (even more so if I use a factory to construct my Parser), but as soon as I switch from Xerces to something else, I need to comb through my code and change all my using namespace XERCES_CPP_NAMESPACE and XERCES_CPP_NAMESPACE::Parser code.
I ran into this recently when I refactored an existing C++ project to split-out some existing useful functionality into a library:
foo.h
class Useful; // Forward Declaration
class Foo
{
public:
Foo(const Useful& u);
...snip...
}
foo.cpp
#include "foo.h"
#include "useful.h" // Useful Library
Foo::Foo(const Useful& u)
{
... snip ...
}
Largely out of ignorance (and partially out of laziness) at the time, the all of the functionality of useful.lib was placed in the global namespace.
As the contents of useful.lib grew (and more clients started to use the functionality), it was decided to move all the code from useful.lib into its own namespace called "useful".
The client .cpp files were easy to fix, just add a using namespace useful;
foo.cpp
#include "foo.h"
#include "useful.h" // Useful Library
using namespace useful;
Foo::Foo(const Useful& u)
{
... snip ...
}
But the .h files were really labour intensive. Instead of polluting the global namespace by putting using namespace useful; in the header files, I wrapped the existing forward declarations in the namespace:
foo.h
namespace useful {
class Useful; // Forward Declaration
}
class Foo
{
public:
Foo(const useful::Useful& u);
...snip...
}
There were dozens (and dozens) of files and this ended up being a major pain! It should not have been that difficult. Clearly I did something wrong with either the design and/or implementation.
Although I know that library code should be in its own namespace, would it have been advantageous for the library code to remain in the global namespace, and instead try to manage the #includes?
It sounds to me like your problem is due primarily to how you're (ab)using namespaces, not due to the namespaces themselves.
It sounds like you're throwing a lot of minimally related "stuff" into one namespace, mostly (when you get down to it) because they happen to have been developed by the same person. At least IMO, a namespace should reflect logical organization of the code, not just the accident that a bunch of utilities happened to be written by the same person.
A namespace name should usually be fairly long and descriptive to prevent any more than the most remote possibility of a collision. For example, I usually include my name, date written, and a short description of the functionality of the namespace.
Most client code doesn't need to (and often shouldn't) use the real name of the namespace directly. Instead, it should define a namespace alias, and only the alias name should be used in most code.
Putting points two and three together, we can end up with code something like this:
#include "jdate.h"
namespace dt = Jerry_Coffin_Julian_Date_Dec_21_1999;
int main() {
dt::Date date;
std::cout << "Please enter a date: " << std::flush;
std::cin>>date;
dt::Julian jdate(date);
std::cout << date << " is "
<< jdate << " days after "
<< dt::Julian::base_date()
<< std::endl;
return 0;
}
This removes (or at least drastically reduces) coupling between the client code and a particular implementation of the date/time classes. For example, if I wanted to re-implement the same date/time classes, I could put them in a different namespace, and switch between one and the other just by changing the alias and re-compiling.
In fact, I've used this at times as a kind of compile-time polymorphism mechanism. For one example, I've written a couple versions of a small "display" class, one that displays output in a Windows list-box, and another that displays output via iostreams. The code then uses an alias something like:
#ifdef WINDOWED
namespace display = Windowed_Display
#else
namespace display = Console_Display
#endif
The rest of the code just uses display::whatever, so as long as both namespaces implement the entire interface, I can use either one, without changing the rest of the code at all, and without any runtime overhead from using a pointer/reference to a base class with virtual functions for the implementations.
The namespace has nothing to do with coupling. The same coupling exists whether you call it useful::UsefulClass or just UsefulClass. Now the fact that you needed to do all that work refactoring only tells you to what extent your code does depend on your library.
To ease the forwarding you could have written a forward header (there are a couple in the STL, you can surely find it in libraries) like usefulfwd.h that only forward defined the library interface (or implementing classes or whatever you need). But this has nothing to do with coupling.
Still, coupling and namespaces are just unrelated. A rose would smell as sweet by any other name, and your classes are as coupled in any other namespace.
(a) interfaces/classes/functions from the library
Not any more than you already have. Using namespace-ed library components helps you from namespace pollution.
(b) implementation details inferred by the namespace?
Why? All you should be including is a header useful.h. The implementation should be hidden (and reside in the useful.cpp and probably in a dynamic library form).
You can selectively include only those classes that you need from useful.h by having using useful::Useful declarations.
I'd like to expand on the second paragraph of David Rodríguez - dribeas' answer (upvoted):
To ease the forwarding you could have written a forward header (there are a couple in the STL, you can surely find it in libraries) like usefulfwd.h that only forward defined the library interface (or implementing classes or whatever you need). But this has nothing to do with coupling.
I think this points to the core of your problem. Namespaces are a red herring here, you were bitten by underestimating the need to contain syntactic dependencies.
I can understand your "laziness": it is not right to overengineer (enterprise HelloWorld.java), but if you keep your code low-profile in the beginning (which is not necessarily wrong) and the code proves successful, the success will drag it above its league. the trick is to sense the right moment to switch to (or employ from the first moment the need appears) a technique that scratches your itch in a forward compatible way.
Sparkling forward declarations over a project is just begging for a second and subsequent rounds. You don't really need to be a C++ programmer to have read the advice "don't forward-declare standard streams, use <iosfwd> instead" (though it's been a few years when this was relevant; 1999? VC6 era, definitely). You can hear a lot of painful shrieks from programmers who didn't heed the advice if you pause a little.
I can understand the urge to keep it low-brow, but you must admit that #include <usefulfwd.h> is no more pain than class Useful, and scales. Just this simple delegation would spare you N-1 changes from class Useful to class useful::Useful.
Of course, it wouldn't help you with all the uses in the client code. Easy help: in fact, if you use a library in a large application, you should wrap the forward headers supplied with the library in application-specific headers. Importance of this grows with the scope of the dependency and the volatility of the library.
src/libuseful/usefulfwd.h
#ifndef GUARD
#define GUARD
namespace useful {
class Useful;
} // namespace useful
#endif
src/myapp/myapp-usefulfwd.h
#ifndef GUARD
#define GUARD
#include <usefulfwd.h>
using useful::Useful;
#endif
Basically, it's a matter of keeping the code DRY. You might not like catchy TLAs, but this one describes a truly core programming principle.
If you have multiple implementations of your "useful" library, then isn't it equally probable (if not under your control) that they would use the same namespace, whether it be the global namespace or the useful namespace?
Put another way, using a named namespace versus the global namespace has nothing to do with how "coupled" you are to a library/implementation.
Any coherent library evolution strategy should maintain the same namespace for the API. The implementation could utilize different namespaces hidden from you, and these could change in different implementations. Not sure if this is what you mean by "implementation details inferred by the namespace."
no you are not increasing the coupling. As others have said - I dont see how the namespace use leaks the implementation out
the consumer can choose to do
using useful;
using useful::Foo;
useful::Foo = new useful::Foo();
my vote is always for the last one - its the least polluting
THe first one should be strongly discouraged (by firing squad)
Well, the truth is there's no way to easily avoid entanglement of code in C++. Using global namespace is the worst idea, though, because then you have no way to pick between implementations. You wind up with Object instead of Object. This works ok in house because you can edit the source as you go but if someone ships code like that to a customer they should not expect them to be for long.
Once you use the using statement you may as well be in global, but it can be nice in cpp files to use it. So I'd say you should have everything in a namespace, but for inhouse it should all be the same namespace. That way other people can use your code still without a disaster.

Should I wrap all my c++ code in its own namespace?

I come from a c# background where everything has its own namespace, but this practice appears to be uncommon in the c++ world. Should I wrap my code in it's own namespace, the unnamed namespace, or no namespace?
Many C++ developers do not use namespaces, sadly. When I started with C++, I didn't use them for a long time, until I came to the conclusion that I can do better using namespaces.
Many libraries work around namespaces by putting prefixes before names. For example, wxWidgets puts the characters "wx" before everything. Qt puts "Q" before everything. It's nothing really wrong with that, but it requires you to type that prefix all over again, even though when it can be deduced from the context which declarations you mean. Namespaces have a hierarchic order. Names that are lexically closer to the point that reference them are found earlier. So if you reference "Window" within your GUI framework, it will find "my::gui::Window", instead of "::Window".
Namespaces enable some nice features that can't be used without them. For example, if you put your class into a namespace, you can define free functions within that namespace. You then call the function without putting the namespace in front by importing all names, or selectively only some of them into the current scope ("using declaration").
Nowadays, I don't do any project anymore without using them. They make it so easy not to type the same prefix all over again, but still have good organization and avoidance of name-pollution of the global namespace.
Depends, if your code is library code, please wrap it in namespaces, that is the practice in C++. If your code is only a very simple application that doesn't interact with anything else, like a hello world sort of app, there is no need for namespaces, because its redundant.
And since namespaces aren't required the code snippets and examples on the web rarely use them but most real projects do use them.
I just discovered Google's c++ style guide and they have namespace guidelines.
The whole guide is worth reading, but to summarize, they say:
Add unnamed namespaces to .cc files, but not .h files.
Wrap entire (after includes/declarations) .cc and .h files in named namespaces.
Namespaces do not increment the indent level.
At the closing brace for a namespace write } // namespace.
Don't declare anything in std, because it is undefined.
using the using directive is forbidden.
the using declaration is allowed in functions, methods, and classes.
namespace aliases are allowed anywhere.
It really depends upon whether you expect there to be any conflicts.
Two scenarios;
1) If you are creating code that may be used by others (e.g libraries) then there could be namespace clashes so using your own namespace is a good idea.
2) If you are using third-party libraries their code may not be namespaced and could conflict with yours.
I would also say that if you expect your code to be sizable and cover many different areas (math/physics/rendering) then using namespaces does make the code easier to grok, particularly for types that are not obviously classified.
We had problems wrapping code in managed C++ that uses our common libraries here.
Some classes had the same names as System class in the .NET library (i.e. System.Console).
We had to do some ugly macro patches to workaround these problems.
Using namespaces at the beginning would have prevented this.
You only really need namespaces if there's a risk of names conflict - some globally seen function or variable or class is defined more than once. Otherwise you'll do just fine with no namespace - just name your classes so that they don't duplicate runtime library classes and make global functions/variable to be static members of some reasonable classes.
I'd say that it's a good idea, if for no other reason than to keep your stuff from getting stepped on when mixed with other third-party code.
I try to go even farther than that by putting as many variables and functions as I can into classes. But that's sometimes harder to do than it should be (compared to other OO languages).
but this practice appears to be
uncommon in the c++ world
Really. All the code I see seems to be wrapped in a namespace.
I use the same type of convention I see in Java (except I drop the com).
In Java
package com.<Company>.<Product>.<Package>;
In C++
namespace <Company>
{
namespace <Product>
{
namespace <Package>
{
}
}
}