How do I add objects with a custom extension to a cmake library?

巧了我就是萌 提交于 2021-02-07 20:10:54

问题


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!)


回答1:


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.



来源:https://stackoverflow.com/questions/25935811/how-do-i-add-objects-with-a-custom-extension-to-a-cmake-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!