samt1903
samt1903

Reputation: 181

How to declare struct defined in different namespace?

I'm having trouble using a struct that I declared in a different namespace. In File1.h I declare the struct and put it in namespace "Foo".

//File1.h
namespace Foo{
    struct DeviceAddress;
}

struct DeviceAddress {
    uint8_t systemID;
    uint8_t deviceID;
    uint8_t componentID;
};

In File2.c I try to create an instance of that struct:

//File2.c
#include "File1.h"
struct Foo::DeviceAddress bar;

But I get an error for the line in File2.c where I try to declare the struct. The error message is: error C2079: 'bar' uses undefined struct 'Foo::DeviceAddress'

I'm using the MS C++ compiler with Visual Studio as a development environment.

Am I making some sort of syntax error trying to declare 'bar' or am I not understanding something about namespaces or structs?

Upvotes: 5

Views: 15889

Answers (2)

Emil Laine
Emil Laine

Reputation: 42828

The two DeviceAddresses in File1.h are not the same struct: one is inside namespace Foo, the other is in the global namespace.

When you define a struct that's inside a namespace, you have to mention its namespace:

struct Foo::DeviceAddress {
    uint8_t systemID;
    uint8_t deviceID;
    uint8_t componentID;
};

Or simply declare and define it at the same time, which would be the recommended way:

namespace Foo{
    struct DeviceAddress {
        uint8_t systemID;
        uint8_t deviceID;
        uint8_t componentID;
    };
}

Upvotes: 5

Bathsheba
Bathsheba

Reputation: 234685

The problem is in the definition of your struct: it needs to be defined in the namespace too:

namespace Foo {
    struct DeviceAddress {
        uint8_t systemID;
        uint8_t deviceID;
        uint8_t componentID;
    };
}

You're currently defining a separate Foo in the global namespace.

Upvotes: 5

Related Questions