3

I'd like to add some object files to a CMake static library, but they have a custom extension.

Here's what I've tried:

set(SRCS testfile.cxx jsobj.js)
add_library(testlib STATIC ${SRCS})

When made, CMake invokes ar testfile.cxx.o (ie the other file is completely ignored). How do I get it included in the archive? Here are some other tricks I've tried:

list(APPEND CMAKE_CXX_SOURCE_FILE_EXTENSIONS js)
list(APPEND CMAKE_C_SOURCE_FILE_EXTENSIONS js) # no luck

add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/jsobj.js.o
                   COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/jsobj.js
                                                    ${CMAKE_CURRENT_BINARY_DIR}/jsobj.js.o
                   DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/jsobj.js.o) # still no luck

(In case you're interested, I'm using the emscripten compiler, which can accept C/C++ files as source input, and JavaScript files are essentially "precompiled objects". I want to find a way to get CMake to add them to the ar commandline, that's all!)

Nicholas Wilson
  • 9,435
  • 1
  • 41
  • 80

1 Answers1

2

For the record, this is how I solved my problem in a hacky way: "proper" solutions would be gladly accepted.

I made up a new file extension for my special pre-compiled objects, "jso", then added it to the list of input files CMake understands:

list(APPEND CMAKE_CXX_SOURCE_FILE_EXTENSIONS jso)

Then, I add my object files with the extension ".jso" to the CMake sources for inclusion in a static library target.

Finally, I hacked the compiler by setting CC=mycc, where mycc is a Python script which checks if the input has the extension ".jso": if not, it simply re-invokes the standard compiler; otherwise it copies the input to the output with no changes at all, so that mycc -c input.jso -o output.jso.o is just a file copy.

This isn't pretty, but it picks up all the dependencies perfectly for incremental builds. I can't pretend it's pretty, but doing things the way CMake likes seems to work. Here, we're just pretending all inputs are source files, even if they're actually already compiled.

Nicholas Wilson
  • 9,435
  • 1
  • 41
  • 80
  • uao nice! really interesting hack ! thanks you. I needed it for emscripten – CoffeDeveloper Jan 07 '15 at 15:09
  • 1
    I've made a pull request for the emscripten to make this happen automagically -- but the pull request is waiting for me to add some tests to it before it can be accepted. If you want to chip in and help that might be more useful to you! Or at least you should merge in my branch. https://github.com/kripken/emscripten/pull/2809 – Nicholas Wilson Jan 07 '15 at 15:38
  • I wonder why doesn't simply setting `CMAKE__SOURCE_FILE_EXTENSIONS` work? It looks like it is just ignored. – St.Antario Aug 08 '19 at 09:34