cjohnson318
cjohnson318

Reputation: 3253

Nim cross compilation to C

I wrote a Nim program,

echo("Hello.")

And then I tried to cross compile for a Linux machine,

nim c --cpu:i386 --os:linux -c hello.nim

This produced the following output:

config/nim.cfg(45, 2) Hint: added path: '/Users/connor/.babel/pkgs/' [Path]
config/nim.cfg(46, 2) Hint: added path: '/Users/connor/.nimble/pkgs/' [Path]
Hint: used config file '/usr/local/lib/nim-0.10.2/config/nim.cfg' [Conf]
Hint: system [Processing]
Hint: hello [Processing]
Hint: operation successful (8753 lines compiled; 0.140 sec total; 14.148MB)[SuccessX]

At this point I changed into the nimcache/ directory and tried to execute:

gcc hello.c -o hello.o

But that gave me an error:

hello.c:5:10: fatal error: 'nimbase.h' file not found
#include "nimbase.h"
         ^
1 error generated.

I thought, "no biggie, I'll just find nimbase.h and drop it in the nimcache directory there," but after that I got a new error,

In file included from hello.c:5:
./nimbase.h:385:28: error: 'assert_numbits' declared as an array with a
      negative size
  ...sizeof(NI) == sizeof(void*) && NIM_INTBITS == sizeof(NI)*8 ? 1 : -1];
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.

I'm not sure what I'm supposed to do with that. I had tried to use the --genScript option, but that resulted in similar errors. I'm running OS X Yosemite.

Thanks!

Update:

I wasn't sure how many architectures were supported for the --cpu: option, but I found a (partial?) list on the What makes Nim practical blog post. I ended up calling,

nim c --cpu:amd64 --os:linux -c hello.nim

This prevented the error I saw when compiling on my Linux box. If you're using Linux or OS X not sure what your CPU architecture is you can call,

less /proc/cpuinfo

Upvotes: 9

Views: 4156

Answers (2)

Agi Hammerthief
Agi Hammerthief

Reputation: 2134

I was having the same issue getting nim to compile executables for Windows, from a GNU/Linux machine, so I made a bash script. It takes the path to the directory containing *.nim source files and the name of the executable file to output.

I'm sure you could swap out the GCC compiler (MinGW in this case) and change the --os: switch as appropriate:

#!/usr/bin/env bash
# Nim must generate C sources only, to be fed to MingW
nim c --cpu:amd64 --os:windows --opt:speed --embedsrc --threads:on --checks:on -c -d:release $1/*.nim
# Copy nimbase.h so MingW32 can find it during compilation and linking
cp /opt/Nim/lib/nimbase.h $1/nimcache/nimbase.h
mkdir -p $1/bin
cd $1/nimcache && x86_64-w64-mingw32-gcc -save-temps $1/nimcache/*.c -o $1/bin/$2.exe
rm $1/nimcache/*.{i,s} # only care about *.o objects
ls -lAhF $1/nimcache
ls -lAhF $1/bin

Upvotes: 4

uran
uran

Reputation: 1336

The last problem is because you're running gcc for x86_64 arch, while the sources were generated for i386 arch.

Upvotes: 10

Related Questions