Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace and identifier in c++ with dllexport

Does anybody know how this

namespace my_ns {
    void Load() {}
}
using namespace my_ns;
extern "C" __declspec(dllexport) void my_dll_function() {
    ::my_ns::Load();
}

differs from

namespace my_ns {
    void Load() {}
    extern "C" __declspec(dllexport) void my_dll_function() {
        Load();
    }
}

or why one would consider the first one as a better solution than the second?
Please notice the dllexport and extern 'keywords'!

like image 685
Roberto Avatar asked Sep 19 '25 21:09

Roberto


1 Answers

There is no difference (from point of view of a caller inside another DLL), exported function name (because of extern "C") has no reference to namespace (you can check it with Dependency Walker).

It means that it doesn't matter where my_dll_function() is placed, it'll be always imported in the namespace where it'll be declared (with __declspec(dllimport)). This has a somehow big implication: you can't declare more than one exported function (with extern "C") with a given name (even if you - try to - declare them in different namespaces). From C++ specifications (§ 7.5):

...At most one function with a particular name can have C language linkage. Two declarations for a function with C language linkage with the same function name (ignoring the namespace names that qualify it) that appear in different namespace scopes refer to the same function...


Just another side note: in your first example using namespace my_ns is useless because you call function using full namespace ::my_ns::Load().
like image 56
Adriano Repetti Avatar answered Sep 21 '25 14:09

Adriano Repetti