Thread: Wrap code in C into C++ one under Linux

  1. #1
    Registered User
    Join Date
    Sep 2018
    Posts
    25

    Wrap code in C into C++ one under Linux

    Hello all!
    my.c
    Code:
    #define EXPORT __attribute__((visibility("default")))
    EXPORT int foo(void);
    int foo(void)
    {
        extern int _new();
        return _new();
    }
    my.cpp
    Code:
    extern "C" {
    #define EXPORT __attribute__((visibility("default")))        
            EXPORT int foocpp(void)
            {
                extern int foo();
                return foo();
            }
    }
    Then
    g++ -shared -fpic -o lib.so my.cpp my.c asm.s
    where asm.s contains _new.
    I want to call my foocpp using PInvoke from C#:
    Code:
    using System.Runtime.InteropServices;
    class Program{
    [DllImport("lib.so")] public static extern int foocpp ();
     static void Main(string[] args)
            {
                int code = foocpp();
    System.Console.WriteLine(code);
    }
    }
    But on start using
    dotnet run
    I have an error
    symbol lookup error: undefined symbol: foo
    Please, help.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,076
    I think that by invoking g++ to compile my.c, my.c is treated as C++ source rather than C source, so name mangling etc comes into effect without extern "C":
    Quote Originally Posted by gcc 9.3 manual
    g++ is a program that calls GCC and automatically specifies linking against the C++ library. It treats ‘.c’, ‘.h’ and ‘.i’ files as C++ source files instead of C source files unless -x is used.
    (Compiling C++ Programs)
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How do I wrap this?
    By zatlas1 in forum C Programming
    Replies: 3
    Last Post: 07-22-2015, 11:56 AM
  2. Trying to wrap up some code, having problems!
    By Akkernight in forum C++ Programming
    Replies: 2
    Last Post: 04-11-2009, 04:33 PM
  3. It's a wrap!
    By Salem in forum A Brief History of Cprogramming.com
    Replies: 10
    Last Post: 06-10-2007, 02:00 PM
  4. Word Wrap
    By sethjackson in forum Windows Programming
    Replies: 4
    Last Post: 09-21-2005, 04:35 PM

Tags for this Thread