Skip to content

rustc should support compiling C code #1862

Closed
@thoughtpolice

Description

@thoughtpolice

The metaticket is #1850.

Summary: rustc should provide some external means of compiling C files as part of a crate, and referring to it later. Two possible options are:

  1. Just make rustc accept .c files and compile them appropriately.

  2. Add an external attribute that describes a set of .c files and other options that a crate depends on.

I am a fan of 2, particularly because I think it could go well with #[cfg] and it means the rustc driver doesn't have to do stuff like throw options at the C compiler or something.

So I have foo.rc, that has some modules, but I can say:

#[external(c_src="foo.cc ...",
                 cc_opts="-DOMG_HAX")]

#[cfg(target_os = "win32")]
#[external(cc_opts="-DPLATFORM_WIN32")]
...

This makes it easy to compile a lot of C code directly inline with the crate. rustc just handles it in the backend. I feel this is the right approach since rustc may also be aware of other necessary flags, like if you should compile the .c files with -fPIC or not.

Furthermore, according to @brson in #1850, native modules do not strictly have to refer to shared libraries, and instead can use nolink as an attribute. I haven't tried, but perhaps right now it might look like:

#[nolink]
native mod glue {
  fn c_foo_bar(baz: *u8, quux: uint);
}

where c_foo_bar is the externally visible symbol name, that refers to part of the C code you're compiling. Alternatively the module declaration could have some other attribute; I'm not sure if nolink seems to make a lot of sense considering this is a clear use case, but it's not a huge deal here.

Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-frontendArea: Compiler frontend (errors, parsing and HIR)A-linkageArea: linking into static, shared libraries and binariesC-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions