Irritating shortcoming with modules and externs
Jarrett Billingsley
kb3ctd2 at yahoo.com
Tue May 16 15:22:40 PDT 2006
Maybe it's not so much a shortcoming as it is just dumb.
Say I want to create a library which has a "pluggable function." By that I
mean that I want the library to reference an external function, defined by
the user of the library. So, in my library module, I write:
module mod;
extern(D) int intFunc();
void spork()
{
for(int x = intFunc(); x != 0; x = intFunc())
writefln(x);
}
Something purposeless, but it shows that I want to be able to use this
function within this module.
So I compile this to an obj/lib, and create my "host" program which uses the
library. I have this:
module main;
import mod;
int intFunc()
{
static int[5] ints = [4, 3, 2, 1, 0];
static int counter = 0;
counter = (counter + 1) % 5;
return ints[counter];
}
void main()
{
spork();
}
The problem: even though I've defined my intFunc() to match the signature to
be the same as the signature expected by the library, the linker won't
resolve the reference because the function names are mangled with the module
names as well. Meaning that the linker is looking for mod.intFunc, but I've
given it main.intFunc. So I limit the ability to use the library by
dictating that the user define the intFunc in a certain module (and it gets
worse when multiple source levels come up).
One workaround is to put "extern(C)" before the reference in the library and
before the definition, but I don't know if that interferes with the
exception handling stuff.
I doubt there's any robust solution to this, but it's frustrating
nonetheless. This "feature" also dictates that import-only files (to go
along with closed-source modules) must follow the exact directory structure
as the original source so that the mangling matches up, instead of putting
all the declarations into one big import file. A fairly minor
inconvenience, but still..
More information about the Digitalmars-d-learn
mailing list