Comment #0 by CrypticMetaphor88 — 2010-12-09T08:50:08Z
Created attachment 845
Compiling and running in windows command prompt
Code that should not compile, imported from C, compiles on windows, but does
NOT compile on Linux.
Here the example:
// cfile.c file
extern int globalFromD;
void functionFromC(int a) {
globalFromD = a;
}
// end cfile.c
// dfile.d
extern(C) { // this is needed to make it available from C
int globalFromD;
}
extern(C) { // also needed when listing the prototypes for your C functions
void functionFromC(int);
}
import std.stdio; // for writefln
int main() {
globalFromD = 100;
writefln("%d", globalFromD);
functionFromC(500);
writefln("%d", globalFromD);
return 0;
}
// end dfile.d
I compile with:
dmc -c cfile.c
And I get an cfile.obj, which is the object code (.o in gcc).
Then I compile the D code
dmd dfile.d cfile.obj
and I get no errors, so I run it, the result:
// start result
C:\DCode\libtest>dfile.exe
100
100
C:\DCode\libtest>
// end result
I've posted this on the newsgroup( d.D.learn, Subject:"Calling C functions" )
and apparently it's some kind of bug.
More info:
dmc version: 8.42n
dmd version: 2.050
Windows version: Windows XP.
Comment #1 by schveiguy — 2010-12-09T08:56:03Z
I think this is a TLS issue.
The linux errors I got (repeated from NG post):
steves@steve-laptop:~/testd$ gcc -c testc.c
steves@steve-laptop:~/testd$ ~/dmd-2.050/linux/bin/dmd testcallc.d testc.o
/usr/bin/ld: globalFromD: TLS definition in testcallc.o section .tbss mismatches non-TLS reference in testc.o
testc.o: could not read symbols: Bad value
collect2: ld returned 1 exit status
--- errorlevel 1
Comment #2 by bugzilla — 2010-12-09T10:16:40Z
It is a TLS issue. Globals in D2 are allocated in thread local storage, globals in C are not. To make it work, they have to be TLS in both languages, or regular globals in both.
Comment #3 by schveiguy — 2010-12-09T10:19:27Z
So why can the linux compiler detect the issue and not the windows compiler?
Comment #4 by nfxjfg — 2010-12-09T12:16:42Z
Maybe because OPTLINK is a dirty piece of shit and eats any crap without even spitting out warnings?
Comment #5 by bugzilla — 2010-12-09T13:35:59Z
The linux compiler is not detecting the error, the linker is.
The way TLS is implemented is radically different on Windows, Linux, and OSX. Linux does it with special linker fixups, Windows does it with specially generated code. The Windows linker cannot tell that it is supposed to be TLS access.
Comment #6 by nfxjfg — 2010-12-09T13:42:47Z
@Walter: that's very unfortunate, this will cause lots of confusion among new users. Maybe make extern(C) variables __gshared by default?
PS: optlink is a turd anyway. Also looking forward to optlink64.
Comment #7 by schveiguy — 2010-12-09T16:11:48Z
thanks for the explanation.
Perhaps this page needs to note these problems? http://www.digitalmars.com/d/2.0/interfaceToC.html
I'll see if I can do that, I'm going to update this bug as a documentation issue.