4

I'm trying to create a JNI jar with CMake. For that the following has to be done in the appropriate order:

  1. compile .class files
  2. generate .h headers
  3. build native library
  4. jar everything

where

  1. is done with add_jar() (I prefered that at custom_command)
  2. is done with add_custom_command(TARGET ...)
  3. is done with add_library()
  4. is done with add_custom_command(TARGET ...) (because -C option is not supported by add_jar)

How can I ensure that the proper order is followed? I get errors sometimes on the first run.

add_custom_command has a POST/PRE build option, but add_jar and add_library does not. The add_custom_command that does not have the argument TARGET has the DEPENDS option, should I use that?

Is there a way of telling add_library to wait for the 2. custom command to have been ran?

quimnuss
  • 1,503
  • 2
  • 17
  • 37

1 Answers1

8

I guess the error is that you're calling add_library with source files which don't yet exist during the first run of CMake?

If so, you can set the GENERATED property on those source files using the set_source_files_properties command. This lets CMake know that it's OK for those files to not exist at configure-time (when CMake runs), but that they will exist at build-time.

To ensure that the add_jar command executes before add_library, create a dependency on the add_jar target using add_dependencies. To ensure that the add_custom_command command executes before add_library, have the custom command use the TARGET ... PRE_BUILD options.

For example, if your list of sources for the lib is held in a variable called ${Srcs}, you can do:

# Allow 'Srcs' to not exist at configure-time
set_source_files_properties(${Srcs} PROPERTIES GENERATED TRUE)
add_library(MyLib ${Srcs})

# compile .class files
add_jar(MyJarTarget ...)

# generate .h headers
add_custom_command(TARGET MyLib PRE_BUILD COMMAND ...)

# Force 'add_jar' to be built before 'MyLib'
add_dependencies(MyLib MyJarTarget)
Fraser
  • 74,704
  • 20
  • 238
  • 215
  • Awesome. That did it: add_dependencies and knowing that PRE/POST build kind of 'unite' the custom command with the target passed by argument). Actually, what I worked for me is add_jar,then custom_command javah with POST_BUILD on add_jar target, then add_library dependant on the add_jar target and finally custom command POST_BUILD on the library. I am trully happy, I didn't really think it was possible cmake+java – quimnuss Mar 21 '13 at 11:17
  • ah! and thanks for the set_source_files_properties. I didn't like listing the headers manually as their filenames are autogenerated as well. But since while the include directory is known, that's not an issue (unless you're under VS and want the headers on the solution http://stackoverflow.com/questions/1167154/listing-header-files-in-visual-studio-c-project-generated-by-cmake ) – quimnuss Mar 21 '13 at 11:21