1

Let's say that I have implemented a programming language, (we'll call it A for now). A is pretty similiar to C.

I want my users to be able to access functions and data structures from already-existing C libraries. Is this possible? If it is, how would a naive implementation look ?

A

  • is implemented in C++
  • compiles to machine code
  • needs to access closed-source C libraries
sjaustirni
  • 3,056
  • 7
  • 32
  • 50
  • 1
    One naive way is to generate C code from A code – Alex Shesterov Apr 04 '15 at 18:17
  • @Alex Shesterov: This is not an option. Firstly, because **A** compiles to machine code. Secondly, because not all libraries are open-source. I'll update the question. Thanks for the response anyway. – sjaustirni Apr 04 '15 at 18:20
  • 1
    You'll need a copy of the ABI for each platform that **A** supports, and you'll need to produce object files that the C linker understands. Searching SO for `[c] ABI` turns up some threads that may be of interest, e.g. [this post](http://stackoverflow.com/questions/25127874/c-abi-with-llvm) – user3386109 Apr 04 '15 at 18:29

1 Answers1

6

This largely depends on what sort of language A is.

If it is a compiled language, then you need to produce appropriate assembler code (look up "calling conventions", particularly the C calling convention) to call the appropriate C function. If you're using LLVM, you can do this fairly easily by using the declare and call statements. After you've done that, you'll need to link the executable against the C library in question.

If it is an interpreted language, however, then you'll need to dynamically load the library. How you do this is platform-specific: for instance, on unix-type systems, this can be achieved via the dlopen function.

Michael Rawson
  • 1,905
  • 1
  • 15
  • 25
  • So, LLVM has the functionality to access compiled C libraries built-in? – sjaustirni Apr 04 '15 at 18:25
  • 1
    @Dundee: yes, see http://llvm.org/docs/LangRef.html#call-instruction - LLVM is something I'd recommend anyway as it implements a decent optimiser for you. – Michael Rawson Apr 04 '15 at 18:33
  • I wanted to use LLVM anyway, however, I had no idea about this handy feature. I'll definitely use this. Many thanks. – sjaustirni Apr 04 '15 at 18:38