I’m using Cent OS, SWIG 1.3 and I’ve tested to compile the sample Java example from SWIG examples. It consists from:
example.c
/* A global variable */
double Foo = 3.0;
/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) {
int g;
g = y;
while (x > 0) {
g = x;
x = y % x;
y = g;
}
return g;
}
example.i
%module example
extern int gcd(int x, int y);
extern double Foo;
Then I use the command:
swig -java example.i
Then I compile the generated example_wrap.c with:
gcc -c example_wrap.c -I/usr/java/jdk1.6.0_24/include -I/usr/java/jdk1.6.0_24/include/linux
And I have the following errors:
example_wrap.c: In function ‘Java_exampleJNI_Foo_1set’:
example_wrap.c:201: error: ‘Foo’ undeclared (first use in this function)
Is the example.i file wrong or I don’t accomplish something? Or this is a bug in SWIG? Is there a workaround?
You’ve told SWIG that the function and globals will be declared, but you need to make sure that declaration is visible in the generated wrapper code. (You also probably got a warning about an implicit declaration of
gcd, if you didn’t use a higher warning setting for gcc)The solution is to make that declaration visible, the simplest way is:
Personally I’d add an example.h file with those declarations in and the make the module file:
with a corresponding include in example.c for good measure.
An alternative style to write this would be:
But normally I’d only recommend using
%inlinefor cases where what you’re wrapping is specific to the process of wrapping and not a general part of the library you want to wrap.