declaration names collision (newbie question)

Started by
1 comment, last by the_edd 16 years, 3 months ago
Hi all users happy 2008 to all! I have a question that's stopping my project. In my applications i am using two 3rd part libraries, one in C++ the other in plain C. The problem is that the latter (which i tried to add yesterday) declares a lot of variables with the same name of the first library, so i am getting a lot of "error C2872: 'UInt32' ambiguous declaration". The big problem is that, since the library that is giving my headaches is written in plain C, has no namespace declaration inside. Since i can't edit the two libraries, i was wondering if there is a way to separate the names during the inclusion phase. Right now i am using the C library in a .h .cpp couple that have no need of the other library. thanks for any advice, RH
Advertisement
According to msdn you might well be causing the problem yourself by placing your "using" statements in the wrong place (avoid them in .h files, and before the #includes in .cpp files).
One way is to wrap the C library so that you never #include its headers directly. Instead create pass-through functions that use "normal" types, or your own custom types.

So if your 3rd party C library had a header like this:

// widgets.h#ifndef WIDGETS_H_#define WIDGETS_H_typedef unsigned int UInt32;UInt32 make_widget(const char *name);void destroy_widget(UInt32 handle);/* etc... */#end /* WIDGETS_H_ */


you can create widgets_wrapper.h and widgets_wrapper.cpp:

// widgets.h#ifndef WIDGETS_WRAPPER_H_#define WIDGETS_WRAPPER_H_namespace my_stuff{    unsigned int make_widget(const char *name);    void destroy_widget(unsigned int handle);}#end /* WIDGETS_WRAPPER_H_ */


#include "widgets_wrapper.h"#include "3rdpartylib/widgets.h"namespace my_stuff{    unsigned int make_widget(const char *name)    {        return ::make_widget(name);    }    void destroy_widget(unsigned int handle)    {        return ::destroy_widget(handle);    }}


Now you #include "wigdets_wrapper.h" instead of "widgets.h".

Of course, you could (and should) go a stage further) with your wrapper to use RAII and the extras that robust C++ programming demands:

// widgets.h#ifndef WIDGETS_WRAPPER_H_#define WIDGETS_WRAPPER_H_#include <boost/utility.hpp>namespace my_stuff{    //unsigned int make_widget(const char *name);    //void destroy_widget(unsigned int handle);        class widget : boost::noncopyable    {        public:            widget(const std::string &name);            ~widget();        private:            unsigned int handle_;    };}#end /* WIDGETS_WRAPPER_H_ */

This topic is closed to new replies.

Advertisement