简体   繁体   中英

I can PInvoke C++ executable but not shared Library

I do have one .cpp file and when I convert that to an executable using command below:

g++ -std=c++11 command.cpp -o command -lsomereference

If I udnerstand it correctly then it compiles command.cpp into an executable called command and while doing it, it does link my external reference called somereference . Please correct me if my understanding is wrong by any means.

This works very well. In fact, if I remove -lsomereference from my compilation command then it throws a lot of linking errors which tells me that explicit linking to somereference uisng -lsomereference flag is important.

Now,I can reference this executable in my C# program and P/Invoke into main function. so it works all the way to C# code.

Now, my plan is to use it as a P/Invokable library so basically what I need is not an executable but actually a shared library

so after searching it, realized that I have to use -c flag to create a shared library and I used the command below:

g++ -std=c++11 command.cpp -o command.so -c

With this command I can not explicitly link -lsomereference because of -c flag it is going to ignore the linking.

Now, if I try to reference this command.so file into my C# program then it fails with following error:

command.so' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable:

I have no idea what drastically changed between the executable and the .so file(My guess is that executable was compiled with explicit linking) and shared library(command.so) file is compiled with -c flag could be the issue.

What could be breaking command.so file but not the executable ?

The -c flag tells gcc to compile the given file, but not to link anything. What you've done is compile to an object file (.o) and give it a different extension.

The flags you're looking for are -fPIC -shared .

Try this: g++ -std=c++11 -fPIC -shared command.cpp -lsomereference -o command.so

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM