SIP Python/C++ binding fails to compile

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • davidraimosson
    New Member
    • May 2012
    • 5

    SIP Python/C++ binding fails to compile

    Hi all!

    After successfully compiling a Python/C binding with SIP I wanted to do the same thing with Python/C++. For some reason this doesn't work.

    Here's the files:

    fib.cpp
    -----------------------------------------------
    Code:
    #include "fib.h"
    
    int fib1(int n)
    {
    	if (n <= 0) {
    		return 0;
    	} else if (n <= 2) {
    		return 1;
    	} else {
    		return fib1(n-1) + fib1(n-2);
    	}
    }
    fib.h
    -----------------------------------------------
    Code:
    int fib1(int n);
    fib.sip
    -----------------------------------------------
    Code:
    %Module fib
    
    %Include fib.h
    I run the following command to build the intermediate files:
    sip -c . fib.sip

    So far everything works.

    Now I want to build the .pyd file using distutils.

    setup.py
    -----------------------------------------------
    Code:
    from distutils.core import setup, Extension
    import sipdistutils
    
    setup(
      name = 'fib',
      versione = '1.0',
      ext_modules=[
        Extension("fib", ["fib.sip", "fib.cpp"]),
        ],
    
      cmdclass = {'build_ext': sipdistutils.build_ext}
    )
    I run the following command:
    python setup.py build

    This fails with the following error:
    build\temp.win3 2-2.7\Release\sip fibcmodule.cpp: 29:29: error: 'fib1' was not declared in this scope
    error: command 'gcc' failed with exit status 1

    What could the problem be? Shouldn't c++ be used as a compiler instead of gcc, by the way?

    Any help appreciated!

    Kind regards

    David
  • davidraimosson
    New Member
    • May 2012
    • 5

    #2
    Solution found

    I've found a solution that is good enough: namespaces. Next time I'll read the documentation better. I should also mention that a solution with a Fibonacci class could solve the problem, but I didn't find that to be satisfying.

    Below the content of the files can be found.

    fib.cpp

    Code:
    #include "fib.h" 
     
    namespace test 
    { 
        int fib1(int n) 
        { 
            if (n <= 0) { 
                return 0; 
            } else if (n <= 2) { 
                return 1; 
            } else { 
                return fib1(n-1) + fib1(n-2); 
            } 
        } 
    }
    fib.h

    Code:
    namespace test 
    { 
        int fib1(int n); 
    }
    fib.sip

    Code:
    %Module fib 
     
    namespace test { 
        %TypeHeaderCode 
        #include "fib.h" 
        %End 
     
        int fib1(int n); 
    };
    setup.py was left untouched.

    Exactly the same commands as mentioned before were used.

    Comment

    Working...