How to mix C++ and C correctly

前端 未结 2 1156
忘掉有多难
忘掉有多难 2020-11-27 22:16

I am having some problems with this: I need to write a C wrapper for a C++ library. Say I have 3 files:

  • wrapper.h

    typedef struct Foo Foo;
    Fo         
    
    
            
2条回答
  •  隐瞒了意图╮
    2020-11-27 22:34

    You are creating a shared object named a.out, then another shared object named libbindings.so that ostensibly links to a.out but references nothing from it. Now if a set of input files doesn't have any undefined symbols, no libraries are searched or added to the output. So libbindings.so is essentially an empty library. Verify:

     % nm a.out | grep create_foo
     00000000000006bc T create_foo
     % nm libbindings.so | grep create_foo
     %
    

    If you have several source files, you should build an object file from each source (use -c compilation flag), (then optionally combine the objects into a static library --- skip this step if you are not releasing static libraries) then build a shared object from previously built objects:

      clang++ -c -fPIC foo.cpp
      clang++ -c -fPIC bar.cpp
      clang++ -shared -o libfoobar.so foo.o bar.o
    

    If you only have one source, or very few source files you can easily compile together, you can build the shared library in one step:

      clang++ -std=c++14 wrapper.cpp somethingelse.cpp -shared -fPIC -o libbindings.so
    

    This is not recommended for large projects.

提交回复
热议问题