Eric
Eric

Reputation: 19863

How to order headers in .NET C++ projects

I'm trying to build a new .NET C++ project from scratch. I am planning to mix managed and unmanaged code in this project.

this forum thread IDataObject : ambiguous symbol error answers a problem I've seen multiple times.

Post #4 states "Move all 'using namespace XXXX' from .h to .cpp"

this looks like a good idea but now in my header files I need to reference parameters from the .NET Framework like

void loadConfigurations(String^ pPathname);

How am I supposed to move using statements in the .cpp file and use the according namespaces in the .h file?

Upvotes: 0

Views: 261

Answers (4)

nedruod
nedruod

Reputation: 1122

In my experience the only namespace you have to be careful about is System itself. It's somewhat annoying that the most common, most important one is where you find problems, but that's life.

At least you can take comfort that if you're creating managed classes, you're issues with includes will get relief at the assembly barrier, unlike issues with header files for unmanaged classes.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 992707

It's a good idea to always use fully qualified names in header files. Because the using statement affects all following code regardless of #include, putting a using statement in a header file affects everybody that might include that header.

So you would change your function declaration in your header file to:

void loadConfigurations(SomeNamespace::String^ pPathname);

where SomeNamespace is the name of the namespace you were using previously.

Upvotes: 2

itsmatt
itsmatt

Reputation: 31406

To solve this I've done this in the .h file:

namespace TestClassNS
{
  class TestClass;
}

and then in the .cpp file I would #include the .h that TestClass was in and do the using namespaceTestClassNS there.

My C++ is rusty, so there may be a better way.

Upvotes: 0

Evan Teran
Evan Teran

Reputation: 90422

I don't know much about .NET, so my answer only applies to the unmanaged c++ part of your question. Personally, this is one of the main reasons I avoid like the plague "using namespace XXXX;" statements.

I prefer to just be explicit with namespaces like "std::cout << "hello world" << std::endl;"

This avoid namespace collisions and there is never any ambiguity as to where something came from. Also, when you do something like "using namespace std;" you are kinda undoing what namespaces give you. They were designed to avoid collisions and by importing everything into the global, you just invite collisions back in.

This is stricly a matter of opinion and taste.

As for what to do in headers, I just write stuff like this: "void f(const std::string &s);"

Upvotes: 0

Related Questions