how to avoid linkage problems with many function object classes

C

catphive.lists

I have a bunch of function object classes of the form

struct MyFunc : unary_function<arg,ret>
{
MyFunc(arg) : state(arg) {}
void operator() (arg) { /*code here*/ }
};

in various cpp files. Now, the problem is that I happen to write two of
these with the same name in different modules that don't know anything
about each other, I will get a linker error, because the linker won't
be sure of what constructor to link against. How do I protect against
this?

I can't just mark a struct static, as that would only be indicating
that an instance of the struct (if specified) is static *data* and
*not* that the struct itself constructor and member functions itself
has module level linkage only. Is there an actual good way to handle
this?
 
D

David Harmon

On 28 Nov 2006 15:19:42 -0800 in comp.lang.c++, (e-mail address removed)
wrote,
I have a bunch of function object classes of the form

namespace {
struct MyFunc : unary_function<arg,ret>
{
MyFunc(arg) : state(arg) {}
void operator() (arg) { /*code here*/ }
};

};
 
N

Nate Barney

I have a bunch of function object classes of the form

struct MyFunc : unary_function<arg,ret>
{
MyFunc(arg) : state(arg) {}
void operator() (arg) { /*code here*/ }
};

in various cpp files. Now, the problem is that I happen to write two of
these with the same name in different modules that don't know anything
about each other, I will get a linker error, because the linker won't
be sure of what constructor to link against. How do I protect against
this?

Put the struct definitions in the anonymous namespace.
I can't just mark a struct static, as that would only be indicating
that an instance of the struct (if specified) is static *data* and
*not* that the struct itself constructor and member functions itself
has module level linkage only. Is there an actual good way to handle
this?

If you add the static keyword to the beginning of a struct definition,
that means that the struct has internal linkage. This is the old C way
of doing this. The anonymous namespace is the preferred C++ way doing this.

Nate
 
N

Nate Barney

Nate said:
If you add the static keyword to the beginning of a struct definition,
that means that the struct has internal linkage. This is the old C way
of doing this. The anonymous namespace is the preferred C++ way doing
this.

My mistake. I just checked, and the static keyword can only be applied
in this manner to objects and functions.

Nate
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,141
Messages
2,570,814
Members
47,359
Latest member
Claim Bitcoin Earnings. $

Latest Threads

Top