trentforkert / cmake

Experimental CMake with D support
Other
16 stars 2 forks source link

Can't link a C library #21

Closed snosov1 closed 9 years ago

snosov1 commented 9 years ago

Hi! Thanks a lot for doing this work!

I have a problem though. What I'm trying to do is to have a project, that has a D application and a C library.

So, on the top level I have app.d:

import std.stdio;
import clib.sqr;

int main(string[] args)
{
    writeln("Hello, world! ", sqr(3));
    return 0;
}

And CMakeLists.txt:

cmake_minimum_required(VERSION 3.0)

project(ExampleProject D)
include_directories(.)
add_executable(app app.d)

add_subdirectory(clib)
target_link_libraries(app clib)

In the clib subdirectory I have sqr.cpp:

int sqr(int x)
{
    return x * x;
}

sqr.di:

extern(C) int sqr(int x);

And CMakeLists.txt:

project(clib CXX)
add_library(clib sqr.cpp)

The error I get upon building:

-*- mode: compilation; default-directory: "/tmp/testd/build/" -*-
Compilation started at Fri Nov 28 10:56:23

make -k 
[ 50%] Built target clib
[100%] Building D object CMakeFiles/app.dir/app.d.o
Linking D executable app
CMakeFiles/app.dir/app.d.o: In function `_Dmain':
/tmp/testd/app.d:(.text._Dmain+0x24): undefined reference to `sqr'
collect2: ld returned 1 exit status
--- errorlevel 1
make[2]: *** [app] Error 1
make[2]: Target `CMakeFiles/app.dir/build' not remade because of errors.
make[1]: *** [CMakeFiles/app.dir/all] Error 2
make[1]: Target `all' not remade because of errors.
make: *** [all] Error 2
make: Target `default_target' not remade because of errors.

Compilation exited abnormally with code 2 at Fri Nov 28 10:56:23
snosov1 commented 9 years ago

Sorry, the problem turned out to be in name mangling.

When I used project(clib C), it worked fine. When I used extern "C" {} on the C++ side, it also worked fine.

However, it doesn't seem to work with C++ mangling. Even after I change extern(C) int sqr(int x); to extern(C++) int sqr(int x);

Do you know what could be the problem?

OS: Ubuntu 12.04 x86_64 C++ compiler: g++-4.6.3 D compiler: DMD 2.065.0

trentforkert commented 9 years ago

Does the extern(C++) work okay if you do the following?

g++ -o sqr.o -c sqr.cpp
dmd app.d sqr.o
snosov1 commented 9 years ago

Yes, it does. And also, it works with cmake build if I do make clean && make.