https://public.kitware.com/Wiki/api.php?action=feedcontributions&user=Nocnokneo&feedformat=atomKitwarePublic - User contributions [en]2024-03-28T19:35:30ZUser contributionsMediaWiki 1.38.6https://public.kitware.com/Wiki/index.php?title=CMake_FAQ&diff=61969CMake FAQ2017-09-03T01:19:38Z<p>Nocnokneo: Use proper "redirect" term rather than "pipe" for this use case</p>
<hr />
<div>== General information and availability ==<br />
=== What is CMake? ===<br />
CMake is a cross-platform, open-source make system. CMake is used to control the software compilation process using simple platform-independent and compiler-independent configuration files. CMake generates native makefiles and workspaces that can be used in the compiler environment of your choice. CMake is quite sophisticated: it is possible to support complex environments requiring system configuration, preprocessor generation, code generation, and template instantiation. Please go to http://www.cmake.org/overview to learn more about CMake.<br />
<br />
=== What is the current release? ===<br />
The latest release of CMake is always available at: http://www.cmake.org/download<br />
<br />
From there, you can fetch CMake binaries for Windows or several Unix variants, or you can download the source code of CMake.<br />
<br />
You can also access nightly development through Git; see http://www.cmake.org/download for more information. You may also browse the [http://cmake.org/gitweb?p=cmake.git git repository online].<br />
<br />
=== I found a Bug! What should I do? ===<br />
If you have a patch to contribute, please read [http://cmake.org/gitweb?p=cmake.git;a=blob_plain;f=CONTRIBUTING.rst;hb=master CONTRIBUTING.rst] at the top of the CMake source tree.<br />
<br />
Otherwise, please report the bug in our bug tracker: http://www.cmake.org/Bug<br />
<br />
Please make sure to look at the old bugs not to include duplicates, include detailed instructions of the bug and how to reproduce it.<br />
<br />
=== I want a new feature in CMake. What should I do? ===<br />
Report a feature request in our Bug tracker http://www.cmake.org/Bug<br />
<br />
Please make sure to look at the old feature requests not to include duplicates, include detailed instructions of the feature and proposed implementation.<br />
<br />
=== What is the most recent version covered by the Mastering CMake book? ===<br />
A new edition of the [http://www.kitware.com/products/cmakebook.html Mastering CMake] book has been released which documents CMake 2.6.<br />
<br />
The following features have been added since printing the book:<br />
<br />
* New INSTALL command (cmake --help-command INSTALL)<br />
* New LIST command (cmake --help-command LIST)<br />
* Updated FIND_PATH, FIND_PROGRAM, and FIND_FILE commands to be more powerful (cmake --help-command FIND_PATH)<br />
* RPATH and Mac OS X install_name support (cmake --help-command SET_TARGET_PROPERTIES)<br />
* CPack Beta (not finished or documented)<br />
* EXECUTE_PROCESS was added and replaces EXEC_PROGRAM<br />
* Other changes have been bug fixes and internal CMake restructuring<br />
<br />
=== Where can I find searchable CMake Mailing Archives? ===<br />
There exist at least these ones:<br />
* [http://dir.gmane.org/gmane.comp.programming.tools.cmake.user cmake on Gmane]<br />
* [http://www.mail-archive.com/cmake@cmake.org/ http://www.mail-archive.com/cmake@cmake.org/]<br />
* [http://marc.info/?l=cmake http://marc.info/?l=cmake]<br />
* Use google ''site'' keyword in order to search directly in the CMake browsable ML:<br />
site:http://www.cmake.org/pipermail/cmake/ <search terms><br />
<br />
== Running CMake ==<br />
<br />
=== Is there an option to produce more 'verbose' compiling? ===<br />
<br />
On Makefile generators, you can set the Makefile variable VERBOSE to 1. For example on UNIX:<br />
make VERBOSE=1<br />
<br />
You can also set CMAKE_VERBOSE_MAKEFILE to ON.<br />
<br />
On Windows (nmake) you can override CMAKE_VERBOSE_MAKEFILE by using<br />
nmake /S<br />
On Unix make you can mostly override verbose mode by using<br />
make VERBOSE=""<br />
<br />
If you are on Windows using Borland or NMake Makefiles, you will see lines like:<br />
<br />
cl @c:\DOCUME~1\ANDY~1.KIT\LOCALS~1\Temp\nma03504<br />
<br />
The reason for this is that Borland and Microsoft Visual Studio make programs have limitation on the length of command strings. They overcome this limitation by writing arguments to the file and then pass file to the program.<br />
<br />
If you actually want to see what the command looks like, set CMAKE_START_TEMP_FILE and CMAKE_END_TEMP_FILE to "" -- be warned, however, you cannot set these as variables on the CMake command line with -D. Instead, see the very bottom of the file "Modules/Platform/Windows.cmake" and uncomment the lines that set these variables to the empty string.<br />
<br />
=== Is there a way to skip checking of dependent libraries when compiling? ===<br />
<br />
'''Using the Makefile Generator'''<br />
<br />
When using the Makefile generator under *nix you can append "/fast" to your target name. For example:<br />
<br />
make target_name/fast<br />
<br />
Under Windows use a backslash instead:<br />
<br />
make target_name\fast<br />
<br />
'''Using Visual Studio >= 7.1'''<br />
<br />
If you have Visual Studio .NET 7.1 or greater you can use the native option to right click on a project and choose to build just that project.<br />
<br />
'''Using Visual Studio <= 7.0'''<br />
<br />
CMake doesn't try to compile all dependent libraries when you compile a library but it will do so for binary targets. You can't avoid this however you can take advantage of CTRL+F7 to manually compile a source file for the affected target and then relink the target by right clicking on it and choosing Link. You'll have to ensure that all dependent libraries are made up-to-date however or suffer through Visual's slow check.<br />
<br />
=== I set a cmake variable in my environment, but it didn't change anything. Why? ===<br />
CMake build settings are stored in the CMake cache corresponding to a project's build tree. They are called CMake "cache entries" and have no relation to your command shell's environment variables. Use a CMake GUI (CMakeSetup on Windows or ccmake on UNIX) or the wizard mode (cmake -i) to edit cache entries. Initial values may also be specified for a build by using the -D command line argument to cmake when it is first run to produce a new build tree.<br />
<br />
=== How do I use a different compiler? ===<br />
<br />
==== Method 1: use environment variables ====<br />
<br />
For C and C++, set the <tt>CC</tt> and <tt>CXX</tt> environment<br />
variables. This method is not guaranteed to work for all generators.<br />
(Specifically, if you are trying to set Xcode's <tt>GCC_VERSION</tt>,<br />
this method confuses Xcode.)<br />
<br />
For example:<br />
<pre><br />
CC=gcc-4.2 CXX=/usr/bin/g++-4.2 cmake -G "Your Generator" path/to/your/source<br />
</pre><br />
<br />
==== Method 2: use cmake -D ====<br />
<br />
Set the appropriate <tt>CMAKE_FOO_COMPILER</tt> variable(s) to a valid<br />
compiler name or full path on the command-line using <tt>cmake -D</tt>.<br />
<br />
For example:<br />
<pre><br />
cmake -G "Your Generator" -D CMAKE_C_COMPILER=gcc-4.2 -D CMAKE_CXX_COMPILER=g++-4.2 path/to/your/source<br />
</pre><br />
<br />
==== Method 3 (avoid): use set() ====<br />
<br />
Set the appropriate <tt>CMAKE_FOO_COMPILER</tt> variable(s) to a valid<br />
compiler name or full path in a list file using <tt>set()</tt>. This<br />
must be done ''before'' any language is set (ie before any<br />
<tt>project()</tt> or <tt>enable_language()</tt> command).<br />
<br />
For example:<br />
<pre><br />
set(CMAKE_C_COMPILER "gcc-4.2")<br />
set(CMAKE_CXX_COMPILER "/usr/bin/g++-4.2")<br />
<br />
project("YourProjectName")<br />
</pre><br />
<br />
=== I change CMAKE_C_COMPILER in the GUI but it changes back on the next configure step. Why? ===<br />
<br />
Once a build tree is created with a given compiler it cannot be changed. There are a variety of implementation reasons for this policy.<br />
<br />
=== In CCMake, typing full paths is tedious. Is there a better way? ===<br />
Since CMake 1.6, you can use tab completion in the path entries in CCMake. All you do is type first couple of characters and press <TAB> key. CCMake will examine the current typed path and try to expand it to some existing path. If that is possible, it will do it. If not, it will not do anything.<br />
<br />
For example:<br />
<br />
/usr/loc<TAB><br />
<br />
will expand to<br />
<br />
/usr/local/<br />
<br />
<br />
<br />
== Out-of-source build trees ==<br />
<br />
=== What is an "out-of-source" build? ===<br />
When your build generates files, they have to go somewhere. An in-source build puts them in your source tree. An out-of-source build puts them in a completely separate directory, so that your source tree is unchanged.<br />
<br />
In the first example, an in-place build is performed, i.e., the binaries are placed in the same directory as the source code.<br />
<br />
cd Hello<br />
ccmake .<br />
make<br />
<br />
In the second example, an out-of-place build is performed, i.e., the source code, libraries, and executables are produced in a directory separate from the source code directory(ies).<br />
<br />
mkdir HelloBuild<br />
cd HelloBuild<br />
ccmake ../Hello<br />
make<br />
<br />
Out-of-source builds are recommended, as you can build multiple variants in separate directories, e.g., HelloBuildDebug, HelloBuildRelease.<br />
<br />
Note: Before performing an out-of-source build, ensure that all CMake generated in-source build information is removed from the source directory, e.g., CMakeFiles directory, CMakeCache.txt.<br />
<br />
=== I run an out-of-source build but CMake generates in-source anyway. Why? ===<br />
This means that there is a CMakeCache.txt file in the source tree, possibly as part of an existing in-source build. If CMake is given the path to a directory with a CMakeCache.txt file, it assumes the directory is a build tree. Therefore if one runs "cmake ../mysrc" to build out-of-source but there is a mysrc/CMakeCache.txt file then cmake will treat mysrc as the build tree.<br />
<br />
This is a side-effect of the feature that allows "cmake ." to be used to regenerate a build tree. The behavior will not be changed because mixing in-source and out-of-source builds is not safe anyway (configured headers may be found in the wrong place).<br />
<br />
=== Why does CMake use full paths, or can I copy my build tree? ===<br />
CMake uses full paths because:<br />
<br />
# configured header files may have full paths in them, and moving those files without re-configuring would cause upredictable behavior.<br />
# because cmake supports out of source builds, if custom commands used relative paths to the source tree, they would not work when they are run in the build tree because the current directory would be incorrect.<br />
# on Unix systems rpaths might be built into executables so they can find shared libraries at run time. If the build tree is moved old executables may use the old shared libraries, and not the new ones.<br />
<br />
Can the build tree be copied or moved?<br />
<br />
The short answer is NO. The reason is because full paths are used in CMake, see above. The main problem is that cmake would need to detect when the binary tree has been moved and rerun. Often when people want to move a binary tree it is so that they can distribute it to other users who may not have cmake in which case this would not work even if cmake would detect the move.<br />
<br />
The workaround is to create a new build tree without copying or moving the old one.<br />
<br />
<br />
=== CMake does not generate a "make distclean" target. Why? ===<br />
Some build trees created with GNU autotools have a "make distclean" target that cleans the build and also removes Makefiles and other parts of the generated build system. CMake does not generate a "make distclean" target because CMakeLists.txt files can run scripts and arbitrary commands; CMake has no way of tracking exactly which files are generated as part of running CMake. Providing a distclean target would give users the false impression that it would work as expected. (CMake does generate a "make clean" target to remove files generated by the compiler and linker.)<br />
<br />
A "make distclean" target is only necessary if the user performs an in-source build. CMake supports in-source builds, but we strongly encourage users to adopt the notion of an out-of-source build. Using a build tree that is separate from the source tree will prevent CMake from generating any files in the source tree. Because CMake does not change the source tree, there is no need for a distclean target. One can start a fresh build by deleting the build tree or creating a separate build tree.<br />
<br />
(If a CMakeLists.txt uses ADD_CUSTOM_COMMAND to generate source files in the source tree, not the build tree, then in CMake 2.2 or higher "make clean" will remove them. See next question.)<br />
<br />
=== Running "make clean" does not remove custom command outputs. Why? ===<br />
In CMake 2.2 and higher custom command outputs should be removed by make clean. Make sure you are using at least this version. Prior to CMake 2.2 custom command outputs were not automatically added to the list of files to clean. In CMake 2.0 the developer can specify a list of files to be deleted. This can be done using SET_DIRECTORY_PROPERTIES setting property ADDITIONAL_MAKE_CLEAN_FILES to the list of files.<br />
<br />
We however strongly recommend using an "out-of-source" build which never writes any files to the source tree. Using a separate source and build tree greatly reduces the need for "make clean" and "make distclean" targets to clean away files that differ between builds.<br />
<br />
<br />
== Writing CMakeLists.txt ==<br />
<br />
=== How to have backward and forward compatibility? ===<br />
<br />
As of CMake 2.6 we employ a "Policy" mechanism to provide backwards compatibility.<br />
The basic requirement for projects is to include one line at the top of the highest CMakeLists.txt file:<br />
<br />
cmake_minimum_required(VERSION 2.6) # or other version<br />
<br />
This tells versions of CMake older than that specified that they are too old to build the project.<br />
They will report this information to the user.<br />
It also tells versions of CMake newer than that specified that the project may not be aware of policies introduced in later versions, which enables additional compatibility.<br />
For futher documentation, see<br />
<br />
* [[CMake_Policies|CMake Policy Mechanism]]<br />
* [http://www.cmake.org/cmake/help/cmake2.6docs.html#command:cmake_policy cmake_policy() command]<br />
* [http://www.cmake.org/cmake/help/cmake2.6docs.html#section_Policies CMake 2.6 Policies]<br />
<br />
=== How do I get the current source or binary directory? ===<br />
The variable CMAKE_CURRENT_SOURCE_DIR contains the absolute path to your current source directory, while CMAKE_CURRENT_BINARY_DIR points to the equivalent binary directory.<br />
<br />
=== Why are my CMake variables not updated in the GUI after a SET command? ===<br />
The cache variables listed in the GUI when you press "Configure" are used to initialize the values seen by the code in CMakeLists.txt files.<br />
<br />
Changes made by the code are used during the configure step and seen by the generators but are not stored back into the cache. For example:<br />
<br />
SET(BUILD_SHARED_LIBS ON)<br />
<br />
will turn on building of shared libraries for the directory containing the command and all subdirectories, but the change will not appear in the GUI.<br />
<br />
You can use the CACHE and FORCE options on the SET command to change variables in a way that will be reflected in the GUI. Run<br />
<br />
cmake --help-command SET<br />
<br />
to see full instructions for the command.<br />
<br />
<br />
=== How can I change the default build mode and see it reflected in the GUI? ===<br />
Adapt the following commands in your CMakeLists.txt (this example sets the Release<br />
With Debug Information mode):<br />
<pre><br />
IF(NOT CMAKE_BUILD_TYPE)<br />
SET(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING<br />
"Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel."<br />
FORCE)<br />
ENDIF(NOT CMAKE_BUILD_TYPE)<br />
</pre><br />
<br />
=== How do I generate an executable, then use the executable to generate a file? ===<br />
<br />
Create the generator executable by just adding a target:<br />
<br />
ADD_EXECUTABLE(generate generate.c)<br />
<br />
The rest of the process is simpler in CMake 2.6 and above than in previous versions.<br />
<br />
Use <code>ADD_CUSTOM_COMMAND</code> to specify a custom build rule for the file.<br />
(In this example we assume <code>generate</code> accepts the input and output files as arguments.)<br />
<br />
ADD_CUSTOM_COMMAND(<br />
OUTPUT someoutput.txt<br />
COMMAND generate ${CMAKE_CURRENT_SOURCE_DIR}/someinput.txt ${CMAKE_CURRENT_BINARY_DIR}/someoutput.txt<br />
DEPENDS generate ${CMAKE_CURRENT_SOURCE_DIR}/someinput.txt<br />
)<br />
<br />
This tells CMake how to build the file but does not actually add a rule to the build system.<br />
Another target must require it.<br />
One may create a custom target explicitly for this rule:<br />
<br />
ADD_CUSTOM_TARGET(driver ALL DEPENDS someoutput.txt)<br />
<br />
or the file may be added as part of some other target:<br />
<br />
ADD_EXECUTABLE(product product.c someoutput.txt)<br />
<br />
<font color=#555555><br />
In CMake 2.4 and below the <code>generate</code> target may not be specified directly in the <code>COMMAND</code> option of <code>add_custom_command</code><br />
(but it can still be used in the <code>DEPENDS</code> option as of CMake 2.4).<br />
Instead use GET_TARGET_PROPERTY to obtain the location of the generated executable.<br />
Additionally, the output must always be specified by full path.<br />
<br />
GET_TARGET_PROPERTY(GENERATE_EXE generate LOCATION)<br />
ADD_CUSTOM_COMMAND(<br />
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/someoutput.txt<br />
COMMAND ${GENERATE_EXE} ${CMAKE_CURRENT_SOURCE_DIR}/someinput.txt ${CMAKE_CURRENT_BINARY_DIR}/someoutput.txt<br />
DEPENDS generate<br />
)<br />
</font><br />
<br />
=== How can I generate a source file during the build? ===<br />
The ADD_CUSTOM_COMMAND command lets you generate a source file that you can then include in another target. For example:<br />
<br />
ADD_CUSTOM_COMMAND(<br />
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/foo.c<br />
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/bar.c ${CMAKE_CURRENT_BINARY_DIR}/foo.c<br />
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/bar.c<br />
)<br />
ADD_EXECUTABLE(foo foo.c)<br />
<br />
This will create an executable by copying bar.c to foo.c and then compiling foo.c to produce foo. CMake allows you to put generated source files in the current source or binary directory, so we were careful to output foo.c to the current binary directory. When we add foo.c to foo, CMake will look in either directory for it. Even if foo.c does not yet exist, CMake is smart enough to notice that a custom command creates it. (For the file named as the OUTPUT, CMake has its GENERATED source file property set to true.)<br />
<br />
You can also use ADD_CUSTOM_COMMAND when the<br />
[[CMake_FAQ#How_do_I_generate_an_executable.2C_then_use_the_executable_to_generate_a_file.3F|generator command is another executable in the same project]].<br />
<br />
Sometimes, the program doing the generation may generate multiple output files that each need to be part of the build. CMake 2.4 or higher supports having multiple files listed in the OUTPUT section. For example, suppose you had a program that read input.txt and generated three files output1.cpp, output2.h, and output3.cpp, and that those three files needed to be compiled into an executable program. The cmake list file for that would look like this:<br />
<br />
PROJECT(FOO)<br />
# make sure cmake addes the binary directory for the project to the include path<br />
INCLUDE_DIRECTORIES(${FOO_BINARY_DIR})<br />
# add the executable that will do the generation<br />
ADD_EXECUTABLE(my_generator my_generator.cxx)<br />
GET_TARGET_PROPERTY(MY_GENERATOR_EXE my_generator LOCATION)<br />
# add the custom command that will generate all three files<br />
ADD_CUSTOM_COMMAND(<br />
OUTPUT ${FOO_BINARY_DIR}/output1.cpp ${FOO_BINARY_DIR}/output2.h ${FOO_BINARY_DIR}/output3.cpp<br />
COMMAND ${MY_GENERATOR_EXE} ${FOO_BINARY_DIR} ${FOO_SOURCE_DIR}/input.txt<br />
DEPENDS my_generator<br />
MAIN_DEPENDENCY ${FOO_SOURCE_DIR}/input.txt<br />
)<br />
# now create an executable using the generated files<br />
ADD_EXECUTABLE(generated<br />
${FOO_BINARY_DIR}/output1.cpp<br />
${FOO_BINARY_DIR}/output2.h<br />
${FOO_BINARY_DIR}/output3.cpp)<br />
<br />
CMake 2.4 allows you to generate a header file. Because generated headers often cause unnecessary rebuilds, you should try to avoid them; consider using the CONFIGURE_FILE command to prepare the header at CMake time. If you must generate a header file, use code like this:<br />
<br />
ADD_CUSTOM_COMMAND(<br />
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/foo.h<br />
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/bar.h ${CMAKE_CURRENT_BINARY_DIR}/foo.h<br />
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/bar.h<br />
)<br />
ADD_EXECUTABLE(foo foo.c ${CMAKE_CURRENT_BINARY_DIR}/foo.h)<br />
<br />
This is like the first example above, except that it generates a header instead of a C file. The header might not exist when the build system scans foo.c's dependencies, so there is no way for CMake to know that this target requires foo.h unless we can tell it that foo.h may exist in the future. We give CMake this knowledge by listing the generated header file in the set of source files for the target. (This requires CMake 2.4. Previous versions of CMake required use of the OBJECT_DEPENDS source file property.)<br />
<br />
=== How can I add a dependency to a source file which is generated in a subdirectory? ===<br />
<br />
Rules created with <code>ADD_CUSTOM_COMMAND</code> as [[CMake_FAQ#How_can_I_generate_a_source_file_during_the_build.3F|above]] have scope only in the directory in which they are specified.<br />
If the generated file is needed in another directory, a target-level dependency needs to be added.<br />
Create a target in the subdirectory with the custom rule in order to drive it:<br />
<br />
# subdir/CMakeLists.txt<br />
ADD_CUSTOM_COMMAND(<br />
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/foo.c<br />
COMMAND ${CMAKE_COMMAND} copy ${CMAKE_CURRENT_SOURCE_DIR}/bar.c ${CMAKE_CURRENT_BINARY_DIR}/foo.c<br />
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/bar.c<br />
)<br />
ADD_CUSTOM_TARGET(generate_foo DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/foo.c)<br />
<br />
Now other targets can depend on the target from the subdirectory:<br />
<br />
# CMakeLists.txt<br />
ADD_SUBDIRECTORY(subdir)<br />
# Create the executable.<br />
ADD_EXECUTABLE(generated ${CMAKE_CURRENT_BINARY_DIR}/subdir/foo.c)<br />
# Tell CMake the source won't be available until build time.<br />
SET_SOURCE_FILES_PROPERTIES(${CMAKE_CURRENT_BINARY_DIR}/subdir/foo.c PROPERTIES GENERATED 1)<br />
# Make sure the source is generated before the executable builds.<br />
ADD_DEPENDENCIES(generated generate_foo)<br />
<br />
=== How can I generate a file used in more than one target in the same directory? ===<br />
<br />
CMake will generate a copy of a custom command in the build rules for every target that lists the custom command output as a source file.<br />
There is no other place to put it.<br />
If a single custom command output is listed in more than one target and the targets have no dependency relationship they will race to run the custom command during a parallel build and possibly clobber each other.<br />
For example:<br />
<br />
add_custom_command(OUTPUT Foo.c COMMAND ... DEPENDS ...)<br />
add_library(FooStatic STATIC Foo.c)<br />
add_library(FooShared SHARED Foo.c)<br />
<br />
There are at least two solutions to this problem.<br />
First, one may use add_dependencies to serialize the targets involved:<br />
<br />
add_dependencies(FooShared FooStatic)<br />
<br />
Second, one may add a custom target dedicated to generating files for the other targets:<br />
<br />
add_custom_target(Foo DEPENDS Foo.c)<br />
add_dependencies(FooStatic Foo)<br />
add_dependencies(FooShared Foo)<br />
<br />
The latter solution ensures that generated files are up to date before any of the independent targets build so none of them will run the custom command and there will be no race.<br />
<br />
=== I use EXEC_PROGRAM but the result is not set in subdirectories. Why? ===<br />
<br />
An unfortunate holdover from ancient CMake versions is that certain commands are "inherited" into subdirectories and others are not. EXEC_PROGRAM is not inherited. What this means is that when the listfile code from a parent directory executes in a subdirectory the EXEC_PROGRAM command is left out. Therefore the code executes differently. This problem was fixed in CMake 2.2, but for older versions you will have to cache the result:<br />
<br />
<pre><br />
EXEC_PROGRAM(my-program OUTPUT_VARIABLE MY_OUTPUT)<br />
SET(MY_OUTPUT "${MY_OUTPUT}" CACHE INTERNAL "")<br />
</pre><br />
<br />
This will store the result in a global location so it will be available in the subdirectory. Be sure to choose a descriptive name for MY_OUTPUT to avoid conflict in the global setting.<br />
<br />
=== How can I get or set environment variables? ===<br />
<br />
CMake names environment variables using an ENV prefix and surrounding the names in curly braces. Here is an example:<br />
<br />
<pre><br />
MESSAGE("$ENV{PATH}")<br />
</pre><br />
<br />
Reading variables will work in any version of CMake. Writing to them works in CMake 2.2 and higher using the following syntax:<br />
<br />
<pre><br />
SET(ENV{HELLO} "World")<br />
</pre><br />
<br />
Note that there is currently no way to tell apart an empty environment variable value from a variable that is not set at all.<br />
<br />
One should avoid using environment variables for controlling the flow of CMake code (such as in IF commands). The build system generated by CMake may re-run CMake automatically when CMakeLists.txt files change. The environment in which this is executed is controlled by the build system and may not match that in which CMake was originally run. If you want to control build settings on the CMake command line, you need to use cache variables set with the -D option. The settings will be saved in CMakeCache.txt so that they don't have to be repeated every time CMake is run on the same build tree.<br />
<br />
Also, environment variables SET in the CMakeLists.txt ''only'' take effect for cmake itself (''configure-time''), so you cannot use this method to set an environment variable that a custom command might need (''build-time''). Barring environment variable support by various CMake commands (e.g. add_custom_command(), currently not supported yet), an acceptable workaround may be to invoke shell scripts instead which wrap the commands to be executed.<br />
<br />
=== Why do I have unwanted semicolons ; in my compiler flags? ===<br />
CMake has a list data type. A list is stored as a string of semicolon-separated list elements. Whitespace separated arguments to a SET statement are interpreted as list elements. For instance, SET(var a b c d e) will give "var" a value of a;b;c;d;e and this list can be used by other CMake commands. However, if you pass ${var} to a non-CMake external tool, such as a compiler's command line, you are passing a;b;c;d;e which is not what you want. Instead you either need to pass "${var}", so that the list will be converted to a whitespace-separated string, or you need to SET(var "a b c d e") in the 1st place so that you're working with a string, not a list.<br />
<br />
=== How can I get quoting and escapes to work properly? ===<br />
If you want to escape a character in CMake, you use "\", like in C code. For example, if you wanted to have a quote embedded in a string you would do this: "\"". However, each level of CMake that processes your code will need one level of escaping to work. So, if you configure a file that is read by cmake or cpack and you want to do the same thing, you would do "\\\"". You would still need to escape the " for the first cmake that processes the string. However, this time, you would want to also escape a '\' as well. This would leave the next level of processing with "\"". Also, for custom commands that may get passed to a shell, it maybe required to do escaping for that shell.<br />
<br />
=== Isn't the "Expression" in the "ELSE (Expression)" confusing? ===<br />
Traditional CMakeLists.txt files prior to 2.6.0, require the following syntax. In the IF syntax, the ELSE section requires the same (Expression) as the IF section. This sometimes can make the script kind of hard to follow, take the short example below:<br />
<br />
IF(WIN32)<br />
...do something...<br />
ELSE(WIN32)<br />
...do something else...<br />
ENDIF(WIN32)<br />
<br />
You might think that the ELSE section, here containing "...do something else...", is for the WIN32 portion of the script. That is not so! It is actually handling the NOT WIN32 section.<br />
<br />
As of CMake 2.6.0 the ELSE() and ENDIF() constructs can be empty. The same is true for closing constructs on ENDMACRO(), ENDFUNCTION(), and ENDFOREACH(). If you require 2.4.x compatibility, CMake 2.4.3 or greater recognizes the CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS option (which is superfluous in 2.6.0)<br />
<br />
cmake_minimum_required(VERSION 2.4.3)<br />
set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS true)<br />
<br />
if(WIN32)<br />
...do something...<br />
elseif(APPLE)<br />
...do something else...<br />
else()<br />
...do something else...<br />
endif()<br />
<br />
=== Which regular expressions are supported by CMake? ===<br />
<br />
(for further details, please refer to the original CMake implementation source at [http://www.cmake.org/cgi-bin/viewcvs.cgi/Source/kwsys/RegularExpression.hxx.in?root=CMake&view=markup Source/kwsys/RegularExpression.hxx.in])<br />
<br />
When using MATCHES or MATCHALL in an IF command, or using any of the STRING(REGEX ...) commands, CMake expects regular expressions, not globs (wild cards). CMake uses the same regular expression engine above all platforms. Here are the meanings of the metacharacters:<br />
<br />
^ Matches at beginning of a line<br />
$ Matches at end of a line<br />
. Matches any single character<br />
[ ] Matches any character(s) inside the brackets<br />
[^ ] Matches any character(s) not inside the brackets<br />
- Matches any character in range on either side of a dash<br />
| Matches a pattern on either side of the |<br />
* Matches preceding pattern zero or more times<br />
+ Matches preceding pattern one or more times<br />
? Matches preceding pattern zero or once only<br />
() Saves a matched expression and uses it in a later match<br />
<br />
Example: "[-][L]([^ ;])+" matches all strings beginning with -L and ending with a space or a semicolon, the usual linkdirs under Linux.<br />
<br />
Here is how to catch a part of a string. The variable test is filled with some content, and then we want to catch the "me":<br />
<br />
SET(test "hello world ! catch: me if you can")<br />
STRING(REGEX REPLACE ".*catch: ([^ ]+).*" "\\1" result "${test}" )<br />
MESSAGE(STATUS "result= ${result}")<br />
<br />
This is slightly tricky. The part inside the brackets is available in \\1 . CMake will copy the variable test to the variable result, but then it will replace everything that the regular expression matches with \\1. This means the first regular expression has to match the whole string and the part we want to catch has to be put in parens.<br />
<br />
-- result= me<br />
<br />
For those of you who know Perl, the equivalent Perl code could be:<br />
<br />
$test = "hello world ! catch: me if you can";<br />
$result = $test;<br />
$result =~ s/.*catch: ([^ ]+).*/$1/;<br />
print "-- result= $result\n";<br />
<br />
There are other ways to do this in Perl, but this is how we do it in CMake because \\1 does not become a variable like $1 does in perl, so there is no SET(result ${\\1}) in CMake.<br />
<br />
<br />
Not sure whether CMake regex implementation supports modifiers for case insensitive matching, thus if this is needed it's perhaps best to do matches on a result of string(TOLOWER ...).<br />
<br />
=== How to convert a semicolon separated list to a whitespace separated string? ===<br />
<br />
set(foo<br />
abc.c<br />
abc.b<br />
abc.a<br />
)<br />
<br />
foreach(arg ${foo})<br />
set(bar "${bar} ${arg}")<br />
endforeach(arg ${foo})<br />
<br />
message("foo: ${foo}")<br />
message("bar: ${bar}")<br />
<br />
=== How can I build multiple modes without switching ? ===<br />
To build multiple modes (e.g. Debug and Release) in one shot without constantly running cmake -DCMAKE_BUILD_TYPE=Debug and cmake -DCMAKE_BUILD_TYPE=Release in source tree create a directory for builds eg.:<br />
<br />
<pre><br />
Project-directory/<br />
/Build<br />
</pre><br />
<br />
Inside you can place as many target directories for out-of-source build modes as you want, e.g.:<br />
<br />
<pre><br />
Project-directory/<br />
/Build<br />
/Debug<br />
/Release<br />
</pre><br />
<br />
In each of these directories issue a command (assuming that you have CMakeLists.txt directly in Project-directory)<br />
<br />
<pre><br />
cmake -DCMAKE_BUILD_TYPE=type_of_build ../../<br />
</pre><br />
<br />
to create a cmake cache configured for requested build type.<br />
<br />
Now you can make each build just by entering appropriate directory and executing a make command.<br />
<br />
=== How can I specify my own configurations (for generators that allow it) ? ===<br />
<br />
For generators that allow it (like Visual Studio), CMake generates four configurations<br />
by default: Debug, Release, MinSizeRel and RelWithDebInfo. Many people just need Debug<br />
and Release, or need other configurations. To modify this, you need to change the<br />
variable CMAKE_CONFIGURATION_TYPES in the cache:<br />
<br />
if(CMAKE_CONFIGURATION_TYPES)<br />
set(CMAKE_CONFIGURATION_TYPES Debug Release DebugMX31 ReleaseMX31)<br />
set(CMAKE_CONFIGURATION_TYPES "${CMAKE_CONFIGURATION_TYPES}" CACHE STRING<br />
"Reset the configurations to what we need"<br />
FORCE)<br />
endif()<br />
<br />
Note that the first line checks whether the generator supports multiple configurations.<br />
<br />
If you just want to add your own configurations while keeping the default ones, you can<br />
use list operations:<br />
<br />
if(CMAKE_CONFIGURATION_TYPES)<br />
list(APPEND CMAKE_CONFIGURATION_TYPES SuperDuper)<br />
list(REMOVE_DUPLICATES CMAKE_CONFIGURATION_TYPES)<br />
set(CMAKE_CONFIGURATION_TYPES "${CMAKE_CONFIGURATION_TYPES}" CACHE STRING<br />
"Add the configurations that we need"<br />
FORCE)<br />
endif()<br />
<br />
=== How can I extend the build modes with a custom made one ? ===<br />
The following code snippet (taken from a CMakeLists.txt) adds a Maintainer mode:<br />
<pre><br />
SET( CMAKE_CXX_FLAGS_MAINTAINER "-Wall -Wabi" CACHE STRING<br />
"Flags used by the C++ compiler during maintainer builds."<br />
FORCE )<br />
SET( CMAKE_C_FLAGS_MAINTAINER "-Wall -pedantic" CACHE STRING<br />
"Flags used by the C compiler during maintainer builds."<br />
FORCE )<br />
SET( CMAKE_EXE_LINKER_FLAGS_MAINTAINER<br />
"-Wl,--warn-unresolved-symbols,--warn-once" CACHE STRING<br />
"Flags used for linking binaries during maintainer builds."<br />
FORCE )<br />
SET( CMAKE_SHARED_LINKER_FLAGS_MAINTAINER<br />
"-Wl,--warn-unresolved-symbols,--warn-once" CACHE STRING<br />
"Flags used by the shared libraries linker during maintainer builds."<br />
FORCE )<br />
MARK_AS_ADVANCED(<br />
CMAKE_CXX_FLAGS_MAINTAINER<br />
CMAKE_C_FLAGS_MAINTAINER<br />
CMAKE_EXE_LINKER_FLAGS_MAINTAINER<br />
CMAKE_SHARED_LINKER_FLAGS_MAINTAINER )<br />
# Update the documentation string of CMAKE_BUILD_TYPE for GUIs<br />
SET( CMAKE_BUILD_TYPE "${CMAKE_BUILD_TYPE}" CACHE STRING<br />
"Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel Maintainer."<br />
FORCE )<br />
</pre><br />
Notes: The flags used in this example are specific to GCC. Change them as needed for your project. Additionally the SET(CMAKE_BUILD_TYPE) command will override<br />
a CMAKE_BUILD_TYPE previously set in the CMakeLists.txt. A simple "SET(CMAKE_BUILD_TYPE)" does silently overwrite, the change is only visible in the GUI if "CACHE" is set when overriding.<br />
<br />
=== Why does <code>foreach</code> skip empty values? ===<br />
<br />
The code in question is of the form<br />
<br />
set(var "a;b;;c;d") # list 'a', 'b', '', 'c', 'd'<br />
foreach(v ${var})<br />
# v=a, v=b, v=c, v=d, one at a time<br />
endforeach()<br />
<br />
and the loop variable 'v' never attains the empty-string value ''.<br />
This is because the <code>${var}</code> syntax is an unquoted argument so the CMake language expands the list and removes the empty value.<br />
The foreach command does not even see the empty value.<br />
One can verify this because the code<br />
<br />
foreach(v a b "" c d)<br />
...<br />
endforeach()<br />
<br />
will see the empty value.<br />
<br />
=== Does CMake support precompiled headers? ===<br />
<br />
Yes and no. Every platform does precompiled headers a bit differently, and there is currently no first-class interface provided by CMake and implemented on every platform.<br />
However, CMake does provide enough primitives for projects to use precompiled headers on specific platforms.<br />
Our issue tracker has a [http://www.cmake.org/Bug/view.php?id=1260 feature request] with attachements providing user-contributed helper macros for some platforms.<br />
<br />
== Writing FindXXX.cmake files ==<br />
<br />
=== What are the rules to write a FindXXX.cmake file? ===<br />
<br />
Let's follow the instructions and the advices in the <br />
Modules/readme.txt [http://www.cmake.org/cgi-bin/viewcvs.cgi/Modules/readme.txt?root=CMake&view=markup]<br />
file located in the CVS repository.<br />
<br />
=== Why does find_library look in system directories before its PATHS option? ===<br />
<br />
The code in question is often of the form<br />
<br />
find_library(FOO_LIBRARY NAMES foo PATHS /opt/foo/lib)<br />
<br />
CMake will find "<code>/usr/lib/libfoo.so</code>" instead of "<code>/opt/foo/lib/libfoo.so</code>" if both exist.<br />
The reason is that /opt/foo/lib is a <i>hard-coded guess</i> of the location.<br />
The documentation of <code>[http://www.cmake.org/cmake/help/cmake2.6docs.html#command:find_library find_library]</code> specifies the search order.<br />
User, project, and system configuration variables are always more local than hard-coded guesses and should override them, so<br />
the PATHS option is used last.<br />
<br />
Some find-modules compute probable locations based on other information <i>available from the system</i> such as a project-specific environment variable.<br />
The HINTS option (CMake 2.6 and higher) takes precedence over system directories specifically for this case:<br />
<br />
file(TO_CMAKE_PATH "$ENV{FOO_LIB_DIR}" FOO_LIB_DIR)<br />
find_library(FOO_LIBRARY NAMES foo HINTS ${FOO_LIB_DIR})<br />
<br />
CMake will find "<code>$ENV{FOO_LIB_DIR}/libfoo.so</code>" before "<code>/usr/lib/libfoo.so</code>".<br />
<br />
== Finding and using external packages ==<br />
<br />
=== How do I use CMake to generate SWIG wrapper libraries? ===<br />
<br />
CMake version 2 includes a module that supports the generation of SWIG wrapper libraries. The SWIG package defines the following macros: SWIG_ADD_MODULE and SWIG_LINK_LIBRARIES.<br />
<br />
<pre><br />
# This example shows how to use python<br />
# Currently these languages have been tested:<br />
# perl tcl ruby php4 pike<br />
<br />
FIND_PACKAGE(SWIG REQUIRED)<br />
INCLUDE(${SWIG_USE_FILE})<br />
<br />
FIND_PACKAGE(PythonLibs)<br />
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})<br />
<br />
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})<br />
<br />
SET(CMAKE_SWIG_FLAGS "")<br />
<br />
SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES CPLUSPLUS ON)<br />
SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "-includeall")<br />
SWIG_ADD_MODULE(example python<br />
example.i example.cxx)<br />
SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES})<br />
<br />
</pre><br />
<br />
<pre><br />
# This example shows how to use tcl<br />
PROJECT(TCL_WRAP)<br />
SET ( MODULE_NAME project )<br />
SET ( INTERFACE_FILES project.i)<br />
SET ( SRC_FILES Vertex.h Vertex.cxx Shapes.h Shapes.cxx )<br />
<br />
FIND_PACKAGE(SWIG REQUIRED)<br />
INCLUDE(${SWIG_USE_FILE})<br />
<br />
# Look for TCL<br />
INCLUDE_DIRECTORIES(${TCL_INCLUDE_PATH})<br />
<br />
FIND_LIBRARY(TCL_LIBRARY NAMES tcl tcl84 tcl83 tcl82 tcl80<br />
PATHS /usr/lib /usr/local/lib)<br />
IF (TCL_LIBRARY)<br />
TARGET_ADD_LIBRARY (${MODULE_NAME} TCL_LIBRARY)<br />
ENDIF (TCL_LIBRARY)<br />
<br />
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})<br />
<br />
SET(CMAKE_SWIG_FLAGS "-c++")<br />
<br />
SET_SOURCE_FILES_PROPERTIES(${INTERFACE_FILES} PROPERTIES CPLUSPLUS ON)<br />
SET_SOURCE_FILES_PROPERTIES(${INTERFACE_FILES} PROPERTIES CMAKE_SWIG_FLAGS "-includeall")<br />
SWIG_ADD_MODULE(${MODULE_NAME} tcl ${INTERFACE_FILES} ${SRC_FILES})<br />
SWIG_LINK_LIBRARIES(${MODULE_NAME} ${TCL_LIBRARIES})<br />
</pre><br />
<br />
If you get errors indicating that C and C++ include files cannot be found, like,<br />
<pre><br />
Error: Unable to find 'string.h'<br />
Error: Unable to find 'time.h'<br />
Error: Unable to find 'string'<br />
Error: Unable to find 'functional'<br />
Error: Unable to find 'utility'<br />
Error: Unable to find 'limits.h'<br />
Error: Unable to find 'fstream'<br />
Error: Unable to find 'sys/times.h'<br />
Error: Unable to find 'unistd.h'<br />
Error: Unable to find 'malloc.h'<br />
...<br />
</pre><br />
try setting the <code>-includeall</code> property on fewer source files:<br />
<pre><br />
# Try doing this on fewer files<br />
SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "-includeall")<br />
</pre><br />
In particular, you may need <code>-includeall</code> only on the top-level <code>.i</code> files.<br />
<br />
=== How do I use CMake to build LaTeX documents? ===<br />
Use the following approach. Note that you have to set LATEX_COMPILE to LaTeX executable, DVIPDF_COMPILE to dvi to pdf converter. Also, the LaTeX source is TDocument.tex and the result is called TDocument.pdf. Note that this uses commands in CMake version 1.8 or later.<br />
<br />
PROJECT(Document)<br />
IF(LATEX_COMPILE)<br />
ADD_CUSTOM_COMMAND(<br />
OUTPUT ${Document_BINARY_DIR}/TDocument.dvi<br />
DEPENDS ${Document_BINARY_DIR}/TDocument.tex<br />
COMMAND ${LATEX_COMPILE} <br />
ARGS ${Document_SOURCE_DIR}/TDocument.tex <br />
)<br />
ENDIF(LATEX_COMPILE)<br />
<br />
IF(DVIPDF_COMPILE)<br />
ADD_CUSTOM_COMMAND(<br />
OUTPUT ${Document_BINARY_DIR}/TDocument.pdf<br />
DEPENDS ${Document_BINARY_DIR}/TDocument.dvi <br />
COMMAND ${DVIPDF_COMPILE}<br />
ARGS ${Document_SOURCE_DIR}/TDocument.dvi<br />
)<br />
ENDIF(DVIPDF_COMPILE)<br />
<br />
ADD_CUSTOM_TARGET(LaTeXDocument ALL echo<br />
DEPENDS ${Document_BINARY_DIR}/TDocument.pdf<br />
)<br />
<br />
The following uses commands in CMake version 2.0 and later<br />
<br />
PROJECT(Document)<br />
# <br />
# Find LaTeX<br />
#<br />
FIND_PACKAGE(LATEX)<br />
<br />
IF(LATEX_COMPILER)<br />
ADD_CUSTOM_COMMAND( <br />
OUTPUT ${Document_BINARY_DIR}/TDocument.dvi<br />
COMMAND ${LATEX_COMPILER}<br />
ARGS ${Document_SOURCE_DIR}/TDocument.tex<br />
DEPENDS ${Document_SOURCE_DIR}/TDocument.tex<br />
COMMENT "Tex2dvi"<br />
)<br />
<br />
IF(DVIPS_CONVERTER)<br />
ADD_CUSTOM_COMMAND( <br />
OUTPUT ${Document_BINARY_DIR}/TDocument.ps<br />
COMMAND ${DVIPS_CONVERTER}<br />
ARGS ${Document_BINARY_DIR}/TDocument.dvi<br />
-o ${Document_BINARY_DIR}/TDocument.ps<br />
DEPENDS ${Document_BINARY_DIR}/TDocument.dvi<br />
COMMENT "dvi2ps"<br />
)<br />
<br />
IF(PS2PDF_CONVERTER)<br />
ADD_CUSTOM_COMMAND( <br />
OUTPUT ${Document_BINARY_DIR}/TDocument.pdf<br />
COMMAND ${PS2PDF_CONVERTER}<br />
ARGS ${Document_BINARY_DIR}/TDocument.ps<br />
DEPENDS ${Document_BINARY_DIR}/TDocument.ps<br />
COMMENT "ps2pdf"<br />
)<br />
<br />
ADD_CUSTOM_TARGET(LaTeXDocument ALL echo<br />
DEPENDS ${Document_BINARY_DIR}/TDocument.pdf<br />
)<br />
ENDIF(PS2PDF_CONVERTER)<br />
ENDIF(DVIPS_CONVERTER)<br />
ENDIF(LATEX_COMPILER)<br />
<br />
=== How do I get LaTeX references to be correct? ===<br />
When your latex document contains references (e.g. \ref{...} command) you get to run two passes of latex. In the<br />
most general case, i.e. when additionally your document uses a bibtex bibliography, you shall need three<br />
passes of latex (and one pass of bibtex):<br />
# latex (first pass: for bibtex to have an .aux file)<br />
# bibtex (for generating the .bbl file)<br />
# latex (second pass)<br />
# latex (third pass)<br />
<br />
The following code snippet illustrates how you can "pervert" the bibtex and latex generated<br />
auxilary files (.aux, .log, .dvi, .bbl...) to create an "artificial" set of CMake dependencies.<br />
The side-effect of those dependencies should hopefully be the above described sequence of calls<br />
to latex and bibtex<br />
<pre><br />
ADD_CUSTOM_COMMAND(<br />
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/UsersManual.aux<br />
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/UsersManual.tex<br />
COMMAND ${LATEX_COMPILER}<br />
ARGS -interaction=batchmode ${CMAKE_CURRENT_BINARY_DIR}/UsersManual<br />
COMMENT "Latex (first pass)"<br />
)<br />
<br />
ADD_CUSTOM_COMMAND(<br />
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/UsersManual.bbl<br />
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/UsersManual.aux<br />
COMMAND ${BIBTEX_COMPILER}<br />
ARGS -terse ${CMAKE_CURRENT_BINARY_DIR}/UsersManual<br />
COMMENT "Bibtex"<br />
)<br />
<br />
ADD_CUSTOM_COMMAND(<br />
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/UsersManual.dvi<br />
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/UsersManual.bbl<br />
COMMAND ${LATEX_COMPILER}<br />
ARGS -interaction=batchmode ${CMAKE_CURRENT_BINARY_DIR}/UsersManual<br />
COMMENT "Latex (second pass)"<br />
)<br />
<br />
ADD_CUSTOM_COMMAND(<br />
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/UsersManual.log<br />
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/UsersManual.bbl<br />
${CMAKE_CURRENT_BINARY_DIR}/UsersManual.dvi<br />
COMMAND ${LATEX_COMPILER}<br />
ARGS -interaction=batchmode ${CMAKE_CURRENT_BINARY_DIR}/UsersManual<br />
COMMENT "Latex (third pass)"<br />
)<br />
# Eventually trigger the whole process<br />
ADD_CUSTOM_TARGET(LaTeXDocument ALL echo<br />
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/UsersManual.log<br />
)<br />
</pre><br />
<br />
=== How can I set TEXINPUTS for a LaTeX compilation? ===<br />
First note that most often you can avoid using TEXINPUTS by copying all the necessary files (.tex source file and<br />
included graphic files e.g. .eps files) from your PROJECT_SOURCE_DIR hirarchy to your PROJECT_BINARY_DIR subdir<br />
[refer to CONFIGURE_FILE with the COPYONLY flag set for copying files]. Since by default latex uses the current working directory as value for TEXINPUTS you should be all set. As expected, this trick is quick AND dirty since your<br />
concerned PROJECT_BINARY_DIR subdir now contains files that are NOT generated by CMake (in the sense that those<br />
files are not the result of a system command but were merely duplicated)... <br />
<br />
If you consider it is cleaner or easier to define a TEXINPUTS environment variable [the latex command probably<br />
misses a -I flag] you can find an example in the InsightDocuments cvs archive (refer to the section "cvs access"<br />
near the bottom of Kitware's ITK download page) or use google with keywords "ITK_TEXINPUTS CONFIGURE_FILE".<br />
Look at InsightDocuments/CourseWare/Training/Vis2003/Latex/CMakeLists.txt and search for e.g. "LaTeXWrapper.sh.in".<br />
<br />
Roughly the mechanism goes:<br />
* SET ITK_TEXINPUTS with the desired TEXINPUTS<br />
* CONFIGURE_FILE "InsightDocuments/CourseWare/Training/Vis2003/LaTeXWrapper.sh.in" which generates an sh shell script setting the shell variable TEXINPUTS prior to running the latex command<br />
* use ADD_CUSTOM_COMMAND to invoke this shell script<br />
This very example is Win32 portable (except that LaTeXWrapper.bat.in generates a .bat shell script)<br />
<br />
== Library questions ==<br />
<br />
=== Can I build both shared and static libraries with one ADD_LIBRARY command? ===<br />
<br />
No. Each library you build must have a unique target name, i.e. the "libname" field of the ADD_LIBRARY command. That way, CMake can track dependencies separately for each library. Libraries can have the same OUTPUT_NAME, see the SET_TARGET_PROPERTIES command, but this is not the default.<br />
<br />
=== Does that mean I have to build all my library objects twice, once for shared and once for static?! I don't like that! ===<br />
<br />
In practice, most libraries have different defines and compiler flags for the shared vs. static cases. So you would have to build all your library objects twice anyways. However, if you happen to have '''''exactly''''' the same defines and compiler flags for the shared vs. static cases...<br />
<br />
...if you're using Linux and a GCC-style linker, you could do the following. Note that for this to work correctly on linux, the zzSTATIC source files should have been compiled with "-fPIC" to ensure they will work in a shared library.<br />
<br />
IF(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_COMPILER_IS_GNUCC)<br />
ADD_LIBRARY(zzSTATIC STATIC -fPIC)<br />
ADD_LIBRARY(zzDYNAMIC SHARED)<br />
TARGET_LINK_LIBRARIES(zzDYNAMIC -Wl,-whole-archive zzSTATIC -Wl,-no-whole-archive)<br />
ENDIF(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_COMPILER_IS_GNUCC)<br />
<br />
...if you want a cross-platform approach that works on all compilers, not just GCC or Linux, you could extract the locations of previously built object files and insert them directly into the libraries that need them. This is documented in [http://www.cmake.org/Bug/view.php?id=5155 CMake Feature Request #5155: standard way to locate object files]. Unfortunately this approach relies on CMake's internal implementation, and that implementation could change in the future, breaking your code.<br />
<br />
=== How do I make my shared and static libraries have the same root name, but different suffixes? ===<br />
Set the OUTPUT_NAME of your shared and static libraries to the same thing.<br />
<br />
ADD_LIBRARY(foo SHARED ${foo_sources})<br />
ADD_LIBRARY(foo-static STATIC ${foo_sources})<br />
# The library target "foo" already has a default OUTPUT_NAME of "foo", so we don't need to change it.<br />
# The library target "foo-static" has a default OUTPUT_NAME of "foo-static", so change it.<br />
SET_TARGET_PROPERTIES(foo-static PROPERTIES OUTPUT_NAME "foo")<br />
# Now the library target "foo-static" will be named "foo.lib" with MS tools.<br />
# This conflicts with the "foo.lib" import library corresponding to "foo.dll",<br />
# so we add a "lib" prefix (which is default on other platforms anyway):<br />
SET_TARGET_PROPERTIES(foo-static PROPERTIES PREFIX "lib")<br />
<br />
One more detail is needed with CMake 2.6.x and lower (but not CMake 2.8 or higher). If you are building your shared and static libraries in the same directory, you will also need the following to keep your shared and static libraries from clobbering each other during the build.<br />
<br />
# Help CMake 2.6.x and lower (not necessary for 2.8 and above, but doesn't hurt):<br />
SET_TARGET_PROPERTIES(foo PROPERTIES CLEAN_DIRECT_OUTPUT 1)<br />
SET_TARGET_PROPERTIES(foo-static PROPERTIES CLEAN_DIRECT_OUTPUT 1)<br />
<br />
=== How do I rename a library after it has already been built? ===<br />
You don't rename it. It's been built! Its name is whatever CMakeLists.txt says it's supposed to be.<br />
<br />
Perhaps you want to copy the library to a different name. But, are you sure that's what you want to do? You could just change the name in your ADD_LIBRARY command or change its OUTPUT_NAME property using SET_TARGET_PROPERTY(). If you really really want to copy the library to a different name, try:<br />
<br />
GET_TARGET_PROPERTY(LIB_NAME Foo LOCATION)<br />
GET_TARGET_PROPERTY(Bar_prefix Foo PREFIX)<br />
GET_TARGET_PROPERTY(Bar_suffix Foo SUFFIX)<br />
SET(NEW_LIB_NAME ${Bar_prefix}Bar${Bar_suffix})<br />
<br />
ADD_CUSTOM_COMMAND(<br />
TARGET Foo<br />
POST_BUILD<br />
COMMAND ${CMAKE_COMMAND} -E copy ${LIB_NAME} ${NEW_LIB_NAME}<br />
)<br />
<br />
On Windows you may also want to copy the .dll import lib, using the same approach as above, but with IMPORT_PREFIX and IMPORT_SUFFIX. ''Problem: LOCATION only refers to 1 file, the .dll. What is a simple way to get the location of the import lib? Could provide a complicated way, but that's annoying.''<br />
<br />
=== Does CMake support "convenience" libraries? ===<br />
No. CMake does not currently support convenience libraries. A "convenience" library, as GNU libtool calls it, is an archive of objects to be mixed into other libraries. Other libraries "link" to the convenience library, but the convenience library does not export any symbols; GNU libtool never installs the convenience library; no programs ever link to the convenience library.<br />
<br />
This does '''not''' mean that a project using convenience libraries cannot be converted to CMake. Instead the source files may be listed in each target that needs them. They will be built for each target separately using all the preprocessor definitions and flags configured for that target.<br />
<br />
=== Why are libraries linked to my shared library included when something links to it? ===<br />
This question arises when one has a library B which links to some library A. When a third target, say C, links to B, CMake will automatically include C to A also. When the libraries are static, then this is always necessary. When the libraries are shared, this is the default behavior provided by CMake with the simple <code>target_link_libraries signature</code>. CMake 3.0 and above provide <code>PUBLIC</code>, <code>PRIVATE</code>, and <code>INTERFACE</code> options to target_link_libraries to specify whether linking should be used for just the implementation and/or made part of the interface (transitive dependencies):<br />
<br />
target_link_libraries(myLibrary PRIVATE myImplDependency)<br />
<br />
CMake 2.8.7 and above provide <code>LINK_PUBLIC</code> and <code>LINK_PRIVATE</code> options for the same purpose (these were superseded by PUBLIC/PRIVATE/INTERFACE in 3.0 for consistency with options other commands like <code>target_compile_definitions</code>).<br />
<br />
=== CMake dependency scanner ===<br />
<br />
CMake does not preprocess source files while scanning dependencies. Code like<br />
<pre><br />
#if 0<br />
# include "bla.h"<br />
#endif<br />
</pre><br />
will result in a dependency on "bla.h". This sometimes leads to source files recompiling unnecessarily but will not break the build.<br />
<br />
== Installation questions ==<br />
<br />
=== Does CMake's "make install" support DESTDIR? ===<br />
'''Yes''', especially when the build-system generator uses CMake's builtin support for installing files: Simply define the DESTDIR environment variable during installation and CMake will treat that value as the root of the file system for all installation paths; naturally, the DESTDIR path must be absolute.<br />
<br />
For example, if the Makefile generator is used, then all of the following are example usages of DESTDIR (perhaps assuming the bash shell for the last 2):<br />
<br />
(1) make install DESTDIR="/some/absolute/path"<br />
(2) make DESTDIR="/some/absolute/path" install<br />
(3) DESTDIR="/some/absolute/path" make install<br />
(4) export DESTDIR="/some/absolute/path<br />
make install<br />
<br />
=== Can I do "make uninstall" with CMake?===<br />
By default, CMake does not provide the "make uninstall" target, so you cannot do this. We do not want "make uninstall" to remove useful files from the system.<br />
<br />
If you want an "uninstall" target in your project, then nobody prevents you from providing one. You need to delete the files listed in install_manifest.txt file. Here is how to do it. First create file cmake_uninstall.cmake.in in the top-level directory of the project:<br />
<br />
<pre>if(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")<br />
message(FATAL_ERROR "Cannot find install manifest: @CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")<br />
endif(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")<br />
<br />
file(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files)<br />
string(REGEX REPLACE "\n" ";" files "${files}")<br />
foreach(file ${files})<br />
message(STATUS "Uninstalling $ENV{DESTDIR}${file}")<br />
if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")<br />
exec_program(<br />
"@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\""<br />
OUTPUT_VARIABLE rm_out<br />
RETURN_VALUE rm_retval<br />
)<br />
if(NOT "${rm_retval}" STREQUAL 0)<br />
message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}")<br />
endif(NOT "${rm_retval}" STREQUAL 0)<br />
else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")<br />
message(STATUS "File $ENV{DESTDIR}${file} does not exist.")<br />
endif(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")<br />
endforeach(file)<br />
</pre><br />
<br />
Then in the top-level CMakeLists.txt add the following logic:<br />
<br />
<pre># uninstall target<br />
configure_file(<br />
"${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake.in"<br />
"${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake"<br />
IMMEDIATE @ONLY)<br />
<br />
add_custom_target(uninstall<br />
COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake)<br />
</pre><br />
<br />
Now you will have an "uninstall" target at the top-level directory of your build tree.<br />
<br />
Instead of creating an "uninstall" target, Unix users could enter this command in the shell:<br />
<br />
xargs rm < install_manifest.txt<br />
<br />
== Distribution questions ==<br />
<br />
=== Where is "make dist"? ===<br />
<br />
CMake doesn't create a "make dist" target.<br />
<br />
=== What is the best way to distribute source code or binaries for a cmake-based project? ===<br />
<br />
For creating source or binary packages there is now [[CMake#CPack | CPack]] coming with CMake, see the <br />
[[ CMake#CPack | documentation]].<br />
<br />
Of course you can also use any other ways to create packages.<br />
<br />
== Platform-specific questions ==<br />
=== How do I build universal binaries on Mac OS X? ===<br />
Before running CMake with an empty build tree, set the CMAKE_OSX_ARCHITECTURES environment variable. It should be set to contain a ; separated list of architectures that you want in the binary. For example, for 32-bit PowerPC and Intel you would do this:<br />
<br />
CMAKE_OSX_ARCHITECTURES=ppc;i386<br />
<br />
If you wish to build both as 32 and 64 bit, do this:<br />
<br />
CMAKE_OSX_ARCHITECTURES=ppc;i386;ppc64;x86_64<br />
<br />
You can also set the same named CMake cache variable on an existing binary tree. This works with both makefiles and the Xcode generator. <br />
<br />
In addition, you can also set the CMAKE_OSX_SYSROOT variable to point to the sysroot (aka Mac OS SDK) to be used. CMake will attempt to pick one on your system, but it can be changed in the cache or via an environment variable before running CMake. The 10.4u SDK or later must be used to create a Universal Binary.<br />
<br />
Universal Binaries are essentially cross compilation and so you should avoid using TRY_RUN, especially for things like testing endianess or variable size because the result will only be correct for one architecture.<br />
<br />
Lastly, note that CTest is only able to test one architecture. See bug 6157.<br />
<br />
=== How can I apply resources on Mac OS X automatically? ===<br />
Using ADD_CUSTOM_COMMAND. For example, let's say you are creating executable MyExecutable, which needs the resources file Carbon.r. All you do is add a custom rule which is executed after the executable is linked:<br />
<br />
<pre><br />
ADD_EXECUTABLE(MyExecutable ${MyExecutable_SRCS})<br />
GET_TARGET_PROPERTY(MyExecutable_PATH MyExecutable LOCATION)<br />
<br />
IF(APPLE)<br />
FIND_PROGRAM(APPLE_RESOURCE Rez /Developer/Tools)<br />
IF(APPLE_RESOURCE)<br />
ADD_CUSTOM_COMMAND(TARGET MyExecutable POST_BUILD<br />
COMMAND ${APPLE_RESOURCE} Carbon.r -o ${MyExecutable_PATH})<br />
ENDIF(APPLE_RESOURCE)<br />
ENDIF(APPLE)<br />
</pre><br />
<br />
This will execute:<br />
<br />
/Developer/Tools/Rez Carbon.r -o /binary/path/MyExecutable<br />
<br />
after MyExecutable is linked.<br />
<br />
'Rez' may be located elsewhere on disk, depending on the version of Mac OS X and Xcode. You can use 'which Rez' in Terminal to find it's full path.<br />
<br />
=== Why does FIND_LIBRARY not find .DLL libraries under WIN32? ===<br />
For those who come from a Unix background to MS Windows:<br />
<br />
You never link directly to the .dll, you have to link against the import library .lib for the .dll.<br />
<br />
Linking against dynamic libraries (.dll under Windows) is quite different from linking against ELF shared objects (.so) under platforms like Linux or NetBSD. In Windows, there are two types of library, a static library and an import library (both confusingly use the .lib extension, however). In Windows, when you build an import library (A.lib) you will get a corresponding (A.dll) that you only need at runtime. At compile time you will need the import library.<br />
<br />
Conclusion: There is no need to find a .dll for linking. You only need to find the .lib import library.<br />
<br />
Some more details can be found here: [http://xenophilia.org/winvunix.html].<br />
<br />
=== Why am I getting a linker error to _mainCRTStartup under WIN32? ===<br />
Your program is a GUI application using WinMain (/subsystem:windows) and not a console application using main. You have to use the WIN32 option with the ADD_EXECUTABLE command.<br />
<br />
ADD_EXECUTABLE(exename WIN32 source1 source2 ... sourceN)<br />
<br />
The second argument to ADD_EXECUTABLE can be WIN32. This indicates that the executable, when compiled on Windows, is a Windows app (using WinMain) and not a console app (using main). Please note that on Unix platforms, CMake ignores the WIN32 and the compiler will use "main" in any case.<br />
<br />
=== Why do I get this error: nafxcwd.lib(appcore.obj) : error LNK2001: unresolved external symbol ___argv ===<br />
<br />
This is because the application is using both the static and dll versions of the MFC library.<br />
To fix the problem, you can do the following:<br />
<br />
SET(CMAKE_MFC_FLAG 2) # force the IDE to use static MFC<br />
ADD_DEFINITIONS(-D_AFXDLL) # make sure if afx.h is included the dll MFC is used<br />
<br />
=== How to use MFC with CMake ===<br />
To use MFC, the CMAKE_MFC_FLAG variable must be set as follows:<br />
<br />
0: Use Standard Windows Libraries<br />
1: Use MFC in a Static Library<br />
2: Use MFC in a Shared DLL <br />
<br />
This can be set in a CMakeLists.txt file and will enable MFC in the application. It should be set to 1 or 2. This is used in visual studio 6 and 7 project files. The CMakeSetup dialog uses MFC and the CMakeLists.txt looks like this:<br />
<br />
ADD_DEFINITIONS(-D_AFXDLL)<br />
SET(CMAKE_MFC_FLAG 2) <br />
ADD_EXECUTABLE(CMakeSetup WIN32 ${SRCS})<br />
<br />
Note that visual studio 9 project files do not appear to work with CMAKE_MFC_FLAG 1; this may be related to [http://www.cmake.org/Bug/view.php?id=7056 bug 7056].<br />
<br />
In order to use MFC with UNICODE, you must also [http://msdn.microsoft.com/en-us/library/dybsewaf.aspx specify the entry point wWinMainCRTStartup]. For example:<br />
<br />
set(CMAKE_MFC_FLAG 2)<br />
set_target_properties(MyApp PROPERTIES<br />
COMPILE_DEFINITIONS _AFXDLL,_UNICODE,UNICODE,_BIND_TO_CURRENT_CRT_VERSION,_BIND_TO_CURRENT_MFC_VERSION<br />
LINK_FLAGS "/ENTRY:\"wWinMainCRTStartup\"")<br />
<br />
See [http://stackoverflow.com/questions/59635/app-does-not-run-with-vs-2008-sp1-dlls-previous-version-works-with-rtm-versions this article] as to why _BIND_TO_CURRENT_CRT_VERSION and _BIND_TO_CURRENT_MFC_VERSION are necessary for Visual Studio 2008 SP1.<br />
<br />
=== How To Put Files in Folders in Visual Studio Projects ===<br />
The Visual Studio IDE supports putting files into folders.<br />
CMake can be used to put files in folders with the SOURCE_GROUP <br />
command. <br />
<br />
SOURCE_GROUP(name [REGULAR_EXPRESSION regex] [FILES src1 src2 ...])<br />
<br />
Defines a group into which sources will be placed in project files. This is mainly used to setup file tabs in Visual Studio. Any file whose name is listed or matches the regular expression will be placed in this group provided the source file is being passed to ADD_EXECUTABLE or ADD_LIBRARY.<br />
<br />
For example:<br />
SOURCE_GROUP(FooFiles FILES foo.cxx)<br />
SOURCE_GROUP(BarFiles FILES bar.cxx)<br />
ADD_LIBRARY(foo foo.cxx bar.cxx)<br />
<br />
In the event a file matches multiple groups, the LAST group that explicitly lists the file will be favored, if any. If no group explicitly lists the file, the LAST group whose regular expression matches the file will be favored. For backwards compatibility this command is also supports the format SOURCE_GROUP(name regex).<br />
<br />
As a convenience to developers CMake automatically adds standard header files to a "Header Files" folder and standard source files to a "Source Files" folder for Visual Studio Projects. This can be overridden via the SOURCE_GROUP method documented above.<br />
<br />
=== How to create Visual Studio 6 Projects that contain only a single build type===<br />
For Visual Studio.NET (version 7.0 and above) it is possible to set the CMAKE_CONFIGURATION_TYPES variable to the build type(s) (Debug/Release/...) that you want. This does not work for Visual Studio 6. There is however a way to achieve this. To create your own set of configurations:<br />
<br />
# Create a directory in which you copy the files *.dsptemplate and CMakeVisualStudio6Configurations.cmake from CMake's Templates directory.<br />
# Edit the .cmake file and change the SET(CMAKE_CONFIGURATION_TYPES ...) line to set the build types that you want in your set.<br />
# Edit the *Header.dsptemplate files to contain only the configuration types you want in your set.<br />
# In your CMakeLists.txt file, set the MSPROJECT_TEMPLATE_DIRECTORY to the directory that you created.<br />
<br />
<br />
That's it. Run CMake and your new configuration files will be created.<br />
<br />
Note: Editing the *Header.dsptemplates files should be done very carefully. Here are some guidelines:<br />
<br />
- You MUST remove the targets that you do not want in your set at the bottom of the file (e.g. '# Name "OUTPUT_LIBNAME - Win32 MinSizeRel"')<br />
- You can remove the '!IF "$(CFG)" == ...' until '!ELSEIF "$(CFG)" == ...' or '!ELSEIF "$(CFG)" == ...' until '!ENDIF' lines for the configurations you do not want. Make sure that the resulting code still starts with '!IF ...' and ends with '!ENDIF' with any number of '!ELSEIF' sections in between. If you create templates for a single configuration (aka makefile), it is possible to remove everything starting from '!IF' until and including '!ENDIF' and leave only the contents of the relevant section intact.<br />
- Do not edit the lines starting with '!MESSAGE' as the changes may - and probably will - corrupt your resulting DSP files. The only thing I was able to change without corrupting the DSP is to remove the irrevant configurations from the "Possible choices for configuration are:" list.<br />
<br />
If you have only a single configuration in your set, you may want to get rid of the intermediate dir that MsDev creates. You can do that by setting:<br />
# PROP BASE Output_Dir ""<br />
# PROP BASE Intermediate_Dir ""<br />
# PROP Intermediate_Dir ""<br />
# PROP Output_Dir "LIBRARY_OUTPUT_PATH"<br />
or<br />
# PROP Output_Dir "EXECUTABLE_OUTPUT_PATH"<br />
<br />
Additionally you should then also edit the '# ADD LINK32' line in the DLLHeader.dsptemplate file. Change for example '/out:"LIBRARY_OUTPUT_PATHDebug/OUTPUT_LIBNAMEDEBUG_POSTFIX.dll"' into '/out:"LIBRARY_OUTPUT_PATHOUTPUT_LIBNAMEDEBUG_POSTFIX.dll"' (Note that the configuration name and also the slash are removed).<br />
<br />
It is even possible to rename the pre-defined configurations of CMake in this way. Let's say you prefer 'PreProduction' over 'RelWithDebInfo'. You can change the name in the *.dsptemplate files, but you should also change it in the CMakeVisualStudio6Configurations.cmake file. Be careful, however. Only entries relevant to the configuration name should be changed. Do not change the /debug options and the entries that contain the build type in capital characters. Internally in CMake the build type will still remain 'RelWithDebInfo', so also the CMAKE_BUILD_TYPE should be set to the old value. You can only change the way it is named in MSDev.<br />
<br />
Note: Apparently MsDev as command-line build tool only performs a partial check on the build type. It will match all configuration types that CONTAIN the build type in their name. (e.g. if you have renamed RelWithDebInfo to DebugRelease, Debug will build Debug and DebugRelease, Release will build Release and DebugRelease. This may be exactly what you want, but be warned.)<br />
<br />
=== Can CMake set the Debugging/Working Directory property in Visual Studio projects? ===<br />
<br />
Not directly. The value of this property is not stored in the project files. It is stored in extra files created by the IDE when a solution is loaded (VS .NET 2003 uses a hidden .suo file next to the .sln solution file). The format of these files is not known to CMake and cannot be generated. In some versions of VS the files are binary and not human readable.<br />
<br />
However, for Visual Studio versions at least 2005 and newer, [[User:Rpavlik|Ryan Pavlik]] maintains CMake modules that can create these files: [https://github.com/rpavlik/cmake-modules/blob/master/CreateLaunchers.cmake main script], also requires [https://github.com/rpavlik/cmake-modules/tree/master/launcher-templates this directory].<br />
<br />
=== Why does CMakeSetup with the message "LINK : fatal error LNK1104: cannot open file 'user32.lib'" while configuring a project? ===<br />
<br />
The path to the SDK libs (user32.lib) must be added by the IDE when the<br />
project generator "Visual Studio 8 2005" is used, because cmake uses<br />
VCExpress.exe and on the fly generated project files to check<br />
for compiling (VCExpress.exe reads some config files for the<br />
compiler/linker options)<br />
<br />
So add the sdk lib path (...\Microsoft Platform SDK\Lib) at Tools->Options->Projects and Solutions->VC++ Directories->Library files<br />
<br />
See also:<br />
*http://msdn.microsoft.com/vstudio/express/visualc/usingpsdk/<br />
<br />
=== How can I avoid the error "Arg list too long" when running make? ===<br />
This error is sometimes encountered when building a static library with many object files using Unix make command. It typically looks something like this:<br />
<br />
<pre><br />
gmake[2]: execvp: /bin/sh: Arg list too long<br />
</pre><br />
<br />
When make tries to run the archiver program to build the static library the shell it uses complains that the argument list is too long. In some shells this can be fixed by setting an environment variable such as <tt>ARG_MAX</tt> to extend the length of the command line it will allow.<br />
<br />
The error can also happen when linking shared libraries, and can be solved by upping the sysconf parameter MAX_ARG. <br />
<br />
On AIX this can be done with the command:<br />
<br />
<pre><br />
chdev -l sys0 -a ncargs='30'<br />
</pre><br />
<br />
Obviously an alternative approach might be to contemplate reducing the object count by splitting off some suitable group of objects into their separate static library.<br />
<br />
=== How can I find out platforms definitions, search paths, etc. from gcc ?===<br />
<br />
The following is really the best if not only way to get information about predefined macros with a GNU compiler:<br />
<pre><br />
$ touch empty.c<br />
$ gcc -v -dD -E empty.c <br />
</pre><br />
This will give you all you might want to know about the preprocessor, the builtin include search dirs and all<br />
predefined definitions, so you can check whether it's __LINUX or _LINUX_ or _APPLE_ or __APPLE etc. <br />
The empty file and all these parameters are really required. You probably want to redirect the output (both stdout and stderr) to a file.<br />
If you want the information for C++, use a C++ file suffix for the empty file.<br />
<br />
This is how you can get the builtin library search paths:<br />
<pre><br />
$ gcc --print-search-dirs<br />
</pre><br />
<br />
=== How can I get a windows registry key ?===<br />
<br />
The only thing to know is that you can't use just the "SET" command in place of "GET" command.<br />
CMake read the value from the registry only when you "get" it from the cache. For instance :<br />
<br />
<pre><br />
GET_FILENAME_COMPONENT(SDK_ROOT_PATH "[HKEY_LOCAL_MACHINE\\SOFTWARE\\PACKAGE;Install_Dir]" ABSOLUTE CACHE)<br />
</pre><br />
<br />
If a key name (ex: Install_Dir in this case) was not specified , the Default key value will be get.<br />
Now you could use the SDK_ROOT_PATH to add include and lib path to your project :<br />
<br />
<pre><br />
INCLUDE_DIRECTORIES(<br />
${SDK_ROOT_PATH}/include<br />
)<br />
<br />
LINK_DIRECTORIES(<br />
${SDK_ROOT_PATH}/lib<br />
)<br />
</pre><br />
<br />
You can also read a registry key in the PATHS section of a FIND_LIBRARY, FIND_PATH, FIND_PROGRAM, or FIND_FILE command<br />
FIND_FILE(BOOT_DOT_INI boot.ini PATHS [HKEY_CURRENT_USER\\Environment;HOMEDRIVE])<br />
<br />
For other examples have a look in the CMake Modules folder :<br />
- FindJava.cmake<br />
- FindPythonLibs.cmake<br />
- ..<br />
<br />
=== How can I build my MSVC application with a static runtime? ===<br />
<br />
Here are three options you could employ to compile your MSVC application with /MT instead of /MD.<br />
<br />
==== Manual Replace ====<br />
<br />
You can rely on the user to manually modify CMAKE_C_FLAGS_DEBUG, CMAKE_C_FLAGS_RELEASE, CMAKE_CXX_FLAGS_DEBUG, CMAKE_CXX_FLAGS_RELEASE, etc. within the cache editor. After an initial configure of your software they would have to replace /MD entries with /MT.<br />
<br />
==== Make Override Files ====<br />
<br />
If you intend to build the entire source tree using /MT and you don't<br />
need this ever to be configurable via the CMake GUI, the best approach<br />
is to create an override file which initializes the starting cache<br />
values for the compile flags.<br />
<br />
First create a c_flag_overrides.cmake & cxx_flag_overrides.cmake file which<br />
contain something like this... (or whatever flags you wish to use per compiler).<br />
<br />
c_flag_overrides.cmake<br />
if(MSVC)<br />
set(CMAKE_C_FLAGS_DEBUG_INIT "/D_DEBUG /MTd /Zi /Ob0 /Od /RTC1")<br />
set(CMAKE_C_FLAGS_MINSIZEREL_INIT "/MT /O1 /Ob1 /D NDEBUG")<br />
set(CMAKE_C_FLAGS_RELEASE_INIT "/MT /O2 /Ob2 /D NDEBUG")<br />
set(CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "/MT /Zi /O2 /Ob1 /D NDEBUG")<br />
endif()<br />
<br />
cxx_flag_overrides.cmake<br />
if(MSVC)<br />
set(CMAKE_CXX_FLAGS_DEBUG_INIT "/D_DEBUG /MTd /Zi /Ob0 /Od /RTC1")<br />
set(CMAKE_CXX_FLAGS_MINSIZEREL_INIT "/MT /O1 /Ob1 /D NDEBUG")<br />
set(CMAKE_CXX_FLAGS_RELEASE_INIT "/MT /O2 /Ob2 /D NDEBUG")<br />
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "/MT /Zi /O2 /Ob1 /D NDEBUG")<br />
endif()<br />
<br />
'''NOTE:''' These files are only evaluated on the first run of CMake so they can't be dependent on a CMake option() meant to be toggled from the GUI, for example. They could be dependent on a command line -D option or an environment variable if desired.<br />
<br />
Then enable them by setting the following variables prior to the project() command.<br />
<br />
set(CMAKE_USER_MAKE_RULES_OVERRIDE<br />
${CMAKE_CURRENT_SOURCE_DIR}/c_flag_overrides.cmake)<br />
set(CMAKE_USER_MAKE_RULES_OVERRIDE_CXX<br />
${CMAKE_CURRENT_SOURCE_DIR}/cxx_flag_overrides.cmake)<br />
project(Bar)<br />
<br />
==== Dynamic Replace ====<br />
<br />
Alternatively, if you need dynamic control of /MT via some configure option you could use the following technique. Note: CMAKE_CXX_FLAGS_<FOO> is a directory level option, however. Also, this option has the downside of leaving /MD visible in the cache editor although it has no effect.<br />
<br />
foreach(flag_var<br />
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE<br />
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)<br />
if(${flag_var} MATCHES "/MD")<br />
string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")<br />
endif(${flag_var} MATCHES "/MD")<br />
endforeach(flag_var)<br />
<br />
=== Why do generated Xcode projects have a CMake PostBuild Rules phase? ===<br />
<br />
CMake needs precise control over target link command lines that Xcode runs at build time.<br />
Xcode provides a "Link Binary With Libraries" build phase in which one may list files or products from other targets to include when linking.<br />
However, it does not allow arbitrary flags such as "<code>-lfoo</code>" commonly passed by projects to CMake's <code>target_link_libraries</code> command.<br />
It also does not allow ''full'' paths to library files and instead splits /path/to/libfoo.a into -L/path/to and -lfoo which does not guarantee the proper library will be found.<br />
<br />
CMake works around this limitation by putting the entire link line in the <code>OTHER_LDFLAGS</code> build setting where it has full control.<br />
Unfortunately that build setting is just a string, so the resulting build system has no dependency on the files named in the link line.<br />
Furthermore, Xcode does not have any build setting to list arbitrary extra dependencies of the link step.<br />
If any of a target's dependencies are newer than the target's binary Xcode does not know it needs to run the link rule again to bring the target up to date.<br />
<br />
In order to work around the dependency problem, CMake includes in each target a post-build phase that removes the link outputs of all ''other'' targets that ''depend'' on the current target.<br />
This is necessary because all those ''other'' targets lack dependencies on the current target in the generated build system.<br />
Instead when a target finishes building it knows that any other targets that depend on it will be out of date.<br />
The post-build phase removes the other targets so that when it is their turn to build Xcode will re-link them.<br />
<br />
The post-build phase could be avoided if Xcode were to simply provide a setting to specify link dependencies on arbitrary files.<br />
This feature would be useful independent of CMake as it would allow users to add dependencies on files they mention in <code>OTHER_LDFLAGS</code>.<br />
<br />
=== Why does CMake not find my Xcode compiler on OS X with the Unix Makefiles generator? ===<br />
<br />
Xcode 4.3 and later do not install the command-line development tools by default.<br />
One must also install the "Command Line Tools for Xcode" package.<br />
As of Xcode 4.4 one may install it from the Xcode menu:<br />
Xcode -> Preferences -> Downloads -> Components -> Command Line Tools<br />
As of Xcode 4.5 the command-line tools are also available as an independent download that does not require the full Xcode.<br />
<br />
It is also possible to set up a shell environment to run "cmake" and "make" without installing the Command Line Tools package.<br />
<br />
CMake 2.8.10 and greater will recognize when the command-line tools are not installed, find the MacOSX SDK, and add the "-isysroot" flag.<br />
One may use the environment:<br />
<br />
export PATH="$(dirname $(xcrun --find make)):$PATH"<br />
export CC="$(xcrun --find cc)"<br />
export CXX="$(xcrun --find c++)"<br />
<br />
The above environment will work with CMake 2.8.8 and 2.8.9 if one also specifies architectures explicitly (earlier CMake versions are not aware of Xcode 4.3+ SDKs):<br />
<br />
export CMAKE_OSX_ARCHITECTURES=x86_64<br />
<br />
Alternatively one may add "-isysroot" flags via the environment:<br />
<br />
SDK="$(xcodebuild -sdk macosx -version Path)" &&<br />
export CFLAGS="-isysroot $SDK" &&<br />
export CXXFLAGS="-isysroot $SDK" &&<br />
unset SDK<br />
<br />
== Other Questions ==<br />
<br />
=== Why does CMake generate recursive Makefiles? ===<br />
<br />
This question is often asked with reference to this paper:<br />
<br />
* Miller, Peter A., [http://miller.emu.id.au/pmiller/books/rmch/ Recursive Make Considered Harmful], AUUGN Journal of AUUG Inc., 19(1), pp. 14-25, 1998<br />
<br />
The summary of our response may be worded "recursive make considered necessary". CMake ''must'' generate makefiles that invoke other makefiles in order to implement automatic implicit dependency scanning in combination with generated source/header files. Since CMake works with primitive UNIX make tools we may not use GNU make extensions to load new make rules into an already-running make process.<br />
<br />
CMake does not actually generate truly recursive makefiles that follow the directory structure.<br />
It generates a fixed 3-level makefile structure in which each level has a defined purpose:<br />
<br />
# '''Makefile''': Command-line interface entry points. Maps "make" invocations into calls to the level 2 makefile:<br />
#* <code>make -f CMakeFiles/Makefile2 ...</code><br />
# '''CMakeFiles/Makefile2''': Inter-target dependencies. Evaluates targets in dependency order invoking for each target the depends and build steps in level 3:<br />
#* <code>make -f CMakeFiles/$(target).dir/build.make .../depend</code><br />
#* <code>make -f CMakeFiles/$(target).dir/build.make .../build</code><br />
# '''CMakeFiles/<target>.dir/build.make''': File-level dependencies and rules:<br />
#* <code>depend</code>: Evaluates custom commands (to produce generate source files) and then scans sources for implicit dependencies.<br />
#* <code>build</code>: Loads dependency scanning results from previous step. Compiles and links.<br />
<br />
<br />
As a flat-file, minimalistically-designed command-line build alternative to make, using the newly-added (2012) Ninja generator might be worthwhile.<br />
<br />
=== Why can't I make multiple targets on the command line in parallel? ===<br />
<br />
The Makefiles generated by CMake do not support explicit specification of multiple targets on the command line as<br />
<br />
$ make target1 target2 -j<br />
<br />
because it was not a design goal at the time the generators were written.<br />
Insead use<br />
<br />
$ make target1 -j && make target2 -j<br />
<br />
or use add_custom_target and add_dependencies to create a single target depending on both targets and then make that.<br />
<br />
See the multi-level makefile layout described in the answer to the [[#Why_does_CMake_generate_recursive_Makefiles.3F|above question]].<br />
It's the first level's invocation of the second level that needs to be re-worked and perhaps combined in order to fix this limitation.<br />
However, the first level is what allows one to run "make" from any subdirectory to build the targets there along with dependencies so there must be a separate Makefile in each directory.<br />
Supporting both at the same time is not a trivial change from the current design.<br />
<br />
See issue tracker entry [http://www.cmake.org/Bug/view.php?id=14312 14312].<br />
Any proposed solution must work with ancient UNIX make and cannot depend on GNU make features.<br />
<br />
{{CMake/Template/Footer}}</div>Nocnokneohttps://public.kitware.com/Wiki/index.php?title=ITK/Release_Schedule&diff=61116ITK/Release Schedule2017-01-09T16:16:19Z<p>Nocnokneo: update top of page to be consistent with new dates in the table</p>
<hr />
<div>The next feature release is 4.11 scheduled for January, 2017.<br />
<br />
== Release Life Cycle ==<br />
<br />
=== Last period for adding classes and features ===<br />
<br />
* New classes will be selected from good reviews from the Insight Journal<br />
* New features and new methods can be added during this period.<br />
<br />
=== Feature Freeze ===<br />
<br />
* Increase code coverage<br />
** address any UNTESTED files<br />
** address files with code coverage lower than 80%<br />
* Address Run-time memory issues<br />
** Purify reports<br />
** Valgrind reports<br />
<br />
=== RC process ===<br />
<br />
* No new features should merged during the feature freeze, i.e. ''ENH:'' commits, although they can be prepared in Gerrit.<br />
* Release candidates (RC's) will be tagged weekly.<br />
* RC's will be tagged after dashboard examination and discussion at the Friday TCon.<br />
* The repository will be hard frozen to only allow merging by gatekeepers on Wednesday evening before the dashboards start. The freeze will be released after tagging.<br />
* For the final RC, only gatekeeper merges will occur.<br />
<br />
=== Posting Tarballs ===<br />
<br />
* Tarballs are posted to SourceForge<br />
* Tarballs are linked from the ITK Download Page<br />
<br />
== Release 4.11 Schedule ==<br />
<br />
{| border="1"<br />
|- bgcolor="#abcdef"<br />
! Release Number !! Date <br />
|-<br />
| RC Cycles|| January 9th, 2017<br />
|-<br />
| Final Release || January 23rd, 2017<br />
|}<br />
<br />
== Release 4.12 Schedule ==<br />
<br />
{| border="1"<br />
|- bgcolor="#abcdef"<br />
! Release Number !! Date <br />
|-<br />
| RC Cycles|| May 9th, 2017<br />
|-<br />
| Final Release || May 24th, 2017<br />
|}<br />
<br />
== Check-list for Moving Code from IJ to Gerrit and from Gerrit ==<br />
<br />
=== For IJ Articles To Gerrit ===<br />
<br />
* Responsible developer should add a review '''before''' moving into local copy of Gerrit. Please provide authors with feedback regarding changes that were made to conform to ITK style/documentation etc.<br />
<br />
=== For Adding Images to Input or Baseline ===<br />
<br />
* Images should be '''SMALL'''.<br />
** The source tree is not an image database, but a source code repository.<br />
** Adding an image larger than 50Kb should be justified by a discussion in the Developers list<br />
* Regression images should not use Analyze format unless the test is for the AnalyzeImageIO and related classes.<br />
* Images should use non-trivial Metadata.<br />
** Origin should be different form zeros<br />
** Spacing should be different from ones, and it should be anisotropic<br />
** Direction should be different from Identity<br />
<br />
=== For Moving Code From Review ===<br />
* At least one independent (other than contributor) should sign off on the API<br />
* Coverage should be as close to 100% as possible.<br />
** and never lower than 90%.<br />
** For example, itkTransformIOBase.cxx is only at 63% coverage. Should be easily fixed by adding a Print() to one of the tests.<br />
<br />
=== For All ===<br />
* Check all comments for proper English<br />
* Should pass KWStyle. IJ articles should be checked with KWStyle before checking into repository.<br />
* Should pass PrintSelf. IJ articles should pass PrintSelf check before checking into repository.<br />
* Replace itkGetMacro with itkGetConstMacro.<br />
* Header file should contain Insight Journal citation<br />
** Using the "handle" link.<br />
* Progress should be present for all filters. Use itk::SimplerFilterWatcher to exercise progress and PrintSelfs.<br />
* When appropriate, class should handle image directions. Tests should use non-default values for origin, spacing and dimension.<br />
** GaborImageSource did not provide methods to set/get directions.<br />
* Regression tests' names should, when possible, have the same name as the class tested (plus the ''Test'' keyword: e.g. ''itkGaborKernelFunctionTest.cxx'').<br />
* Exceptions should be descriptive and provide as much information as possible<br />
* Member data should be private with access if required through Get methods.<br />
<br />
== Release Changelogs ==<br />
<br />
[[ITK/Releases|Release Changelogs]]</div>Nocnokneohttps://public.kitware.com/Wiki/index.php?title=ITK/Release_4/Modularization/Configure_and_build_ITK&diff=54375ITK/Release 4/Modularization/Configure and build ITK2013-10-30T15:15:04Z<p>Nocnokneo: /* Default mode */ fix typo</p>
<hr />
<div>= CMake options to customizing ITK modules =<br />
<br />
== Default mode ==<br />
<br />
* '''ITK_BUILD_ALL_MODULES''': request to build all the default modules in the toolkit, by default this option is ON.<br />
All non-default modules have "EXCLUDE_FROM_ALL" tags in their module definition files(itk-module.cmake), including the remote modules (source<br />
code located outside of the main ITK repository) and modules who depend on external third-party libraries, such as vtkGlue, BridgeOpenCV, BridgeVXL, etc.<br />
<br />
== Group Options==<br />
<br />
* '''ITKGroup<xxx>''': request to build a group of modules. The source code is organized as such that modules belong to the same group stay in the same group directory. The core group is turned on by default.<br />
<br />
When a group is ON, all the modules in the group and their depending modules are enabled. When a group of OFF, all the modules in the group except the ones that are required by other enabled modules.<br />
<br />
<br />
== Module Options ==<br />
* '''Module_<xxx>''': request to build a module. This option is hidden from the CMake gui when the module is enabled by module dependencies (other modules depend on this module), by the the group option or by the default mode(ITK_BUILD_ALL_MODULES).</div>Nocnokneohttps://public.kitware.com/Wiki/index.php?title=Talk:ITK/Contribute&diff=53767Talk:ITK/Contribute2013-08-05T02:27:48Z<p>Nocnokneo: Created page with "== Page no longer relevant? == The first link on this page points to ITK/Git/Develop which is where are the up-to-date accurate information is. This page seems to just add c..."</p>
<hr />
<div>== Page no longer relevant? ==<br />
<br />
The first link on this page points to [[ITK/Git/Develop]] which is where are the up-to-date accurate information is. This page seems to just add confusion. Shouldn't [http://www.itk.org/Wiki/ITK/FAQ#How_do_I_make_code_contributions_to_ITK.3F this FAQ] point to the [[ITK/Git/Develop]] page? --[[User:Nocnokneo|Nocnokneo]] 22:27, 4 August 2013 (EDT)</div>Nocnokneohttps://public.kitware.com/Wiki/index.php?title=ITK/Release_4/Modularization/Code_Reviews/Checklist&diff=51385ITK/Release 4/Modularization/Code Reviews/Checklist2013-02-05T16:17:03Z<p>Nocnokneo: /* Mini-Pipelines */</p>
<hr />
<div>This page defines the check list to be used by reviewers during the process of reviewing the files in ITKv4.<br />
<br />
__TOC__<br />
<br />
= Major Topics =<br />
<br />
The reviewer will verify the file for compliance with the following major topics<br />
<br />
* Coding Style<br />
* Const correctness<br />
* Mini-Pipelines<br />
* Progress Reporting<br />
* Multi-Threading<br />
* Member variables holding to memory<br />
<br />
The following sections specify the details to be evaluated with each one of these major topics.<br />
<br />
= Coding Style =<br />
<br />
Despite the fact that coding style is verified regularly with KStyle, there are still many details that escape that verification. The following list specifies what elements must be verified by the reviewer.<br />
<br />
* Filename must match class name<br />
* Files must contain a single class<br />
* Implementation of methods must be in the .hxx or .cxx files, not the .h files<br />
* All files must have the [[ITK Copyright Header|Copyright Header]] at the top.<br />
* #define for class name in the .h and .hxx files. __classname_h and __classname_hxx<br />
* Doxygen documentation<br />
** Brief class doxygen description<br />
** Complete class doxygen description<br />
** make sure there is: \ingroup ITKModuleName (ModuleName matching the module it belongs, else ModuleInDoxygenGroup will fail) <br />
* namespace itk<br />
* Classes that use SmartPointers must have<br />
** Constructor/Destructor protected<br />
** Copy Constructor : private and not implemented<br />
** Operator= : private and not implemented<br />
* No acronyms in class name or method names<br />
* No unnecessary headers #included<br />
* Justify every public method<br />
* All member variables must be private<br />
* Use Set/Get Macros (macros should call Modified() to ensure pipeline data is updated)<br />
* If deriving from itkObject<br />
** Use New macro<br />
** declare SmartPointer<T> as Pointer<br />
** declare SmartPointer<const T> as ConstPointer<br />
** declare Self<br />
** declare Superclass<br />
** use TypeMacro<br />
** Have PrintSelf() method and print all the member variables<br />
* 100% code coverage<br />
** Run Utilities/Maintenance/computeCodeCoverageLocallyForOneTest.sh<br />
** Check dashboard<br />
* Any information that is printed or displayed has to be legible to human eyes<br />
* Respect Coding Style as specified in the document Insight/Documentation/Style.pdf<br />
* Must pass the test of KWStyle<br />
* [Style] In the .hxx files of template classes, the first 5 lines in the declaration of methods should be:<br />
** 1) template<br />
** 2) return type<br />
** 3) class name<br />
** 4) ::method name<br />
** 5) the opening bracket<br />
<br />
For example:<br />
<br />
template < template_arguments ><br />
return_type<br />
classname< template_arguments ><br />
::methodsName( method_arguments )<br />
{<br />
// indentation of two spaces<br />
// for the first line of code<br />
int k = 0;<br />
}<br />
<br />
In many cases line (2) uses a trait from the templated class and therefore becomes:<br />
<br />
typename classname< template_arguments >::trait<br />
<br />
== Running KWStyle ==<br />
<br />
=== In a single file ===<br />
<br />
KWStyle -xml ITK.kws.xml itkQuadEdgeMeshTest1.cxx -v<br />
<br />
=== In all the repository ===<br />
<br />
make StyleCheck<br />
<br />
= Const Correctness =<br />
<br />
* Get method must be const<br />
* SetInput methods must take "const raw pointers" as input<br />
* GetOutput methods must give const raw pointers as output<br />
* All non-trivial types must be passed by reference (except for DataObjects, that must be passed by const raw pointers).<br />
* const_cast must only be used inside of the SetInput() method, to overcome the lack of const-correctness in the pipeline.<br />
** overriding GenerateInputRequestedRegion requires const_cast on the inputs<br />
** any other uses of const_cast must be scrutinized<br />
<br />
= Mini-Pipelines =<br />
<br />
Filters that implement a mini-pipeline with N internal filters should<br />
<br />
* Examine that this method is consistent with all filters in mini-pipeline:<br />
<br />
void EnlargeOutputRequestedRegion(DataObject *output)<br />
<br />
* Call ReleaseDataFlagOn() in the first N-1 filters of its mini-pipeline<br />
* For the filters that can run in-place, set them to do so by calling InPlaceOn(). Except the first filter.<br />
* Use the ProgressAccumulator in order to compose a progress report from each one of the internal filters<br />
* Use GraftOutput() in the following way at the end of the GenerateData() method<br />
<br />
caster->GraftOutput( outputImage );<br />
caster->Update();<br />
this->GraftOutput( caster->GetOutput() );<br />
<br />
= Region Management =<br />
<br />
All Filters (supporting streaming or not)<br />
<br />
* In their GenerateData() method they should:<br />
** Only process the Requested Region of the output<br />
** Never access more than the Buffered region of the input<br />
<br />
<br />
If a filter does not support streaming it should:<br />
* Override EnlargeOuputRequestedRegion, and call SetRequestedRegionToLargestPossibleRegion on it's input<br />
* It does not need to override the GenerateInputRequestedRegion<br />
** unless the filter is manipulating the size, or geometry<br />
<br />
= Streaming =<br />
<br />
Filters that are intended for supporting streaming must consider that:<br />
<br />
* The RequestedRegion can be smaller than the LargestPossibleRegion. <br />
<br />
As such, the boundary of the output BufferedRegion may not be a boundary condition and thus the filter writer must implement GenerateInputRequestedRegion to ensure that any pixels outside the output BufferedRegion that are within the LargestPossibleRegion that are needed for proper computation are added to the input RequestedRegion.<br />
<br />
= Progress Reporting =<br />
<br />
Filter should report <br />
<br />
* ProgressEvents or<br />
* IterationEvents<br />
<br />
If they report ProgressEvents, they should use the ProgressReporter class as<br />
<br />
ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() );<br />
<br />
while( ... )<br />
{<br />
// do stuff<br />
progress.CompletedPixel();<br />
}<br />
<br />
If the filter implements a mini-pipeline, then the progress reporting should be done using the ProgressAccumulator inside the GenerateData() method as:<br />
<br />
ProgressAccumulator::Pointer progress = ProgressAccumulator::New();<br />
progress->SetMiniPipelineFilter(this);<br />
<br />
progress->RegisterInternalFilter( internalFilter01, fraction1 );<br />
progress->RegisterInternalFilter( internalFilter02, fraction2 );<br />
progress->RegisterInternalFilter( internalFilter03, fraction3 );<br />
progress->RegisterInternalFilter( internalFilter04, fraction4 );<br />
<br />
<br />
where internalFilterX is each one of the filters in the mini-pipeline, and fractionX are number that add up to 1.0, and represent the fraction of time that each one of the filters will contribute to the total computation. This fraction is assigned as an estimation, and doesn't have to be perfect, just aim for the correct order of magnitude.<br />
<br />
<br />
= Multi-Threading =<br />
<br />
Filters that are multi-threaded, must implement the method:<br />
<br />
void ThreadedGenerateData(<br />
const OutputImageRegionType & outputRegionForThread,<br />
ThreadIdType threadId)<br />
<br />
and can (but do not have to) implement the methods<br />
<br />
void BeforeThreadedGenerateData()<br />
void AfterThreadedGenerateData()<br />
<br />
These two methods are intended to implement the preparation of variables that host computations on every thread, and to consolidate that information once the threads have completed their work.<br />
<br />
The filter should not implement the GenerateData() method, unless it needs anything different from what is provided in the default method in<br />
<br />
ImageSource::GenerateData()<br />
<br />
that essentially does:<br />
<br />
void GenerateData()<br />
{<br />
this->AllocateOutputs();<br />
this->BeforeThreadedGenerateData();<br />
<br />
ThreadStruct str;<br />
str.Filter = this;<br />
<br />
this->GetMultiThreader()->SetNumberOfThreads( this->GetNumberOfThreads() );<br />
this->GetMultiThreader()->SetSingleMethod(this->ThreaderCallback, &str);<br />
<br />
this->GetMultiThreader()->SingleMethodExecute();<br />
<br />
this->AfterThreadedGenerateData();<br />
}<br />
<br />
Any variables that need to be written into during the execution of the ThreadedGenerateData() method, must be put into an array, to provide an independent instance to every thread. This preparation can be done in the BeforeThreadedGenerateData() method, and the consolidation of values in the arrays can be done in the AfterThreadedGenerateData() method.<br />
<br />
== Example ==<br />
<br />
For an example, look at the classes<br />
<br />
* itkStatisticsImageFilter<br />
* itkUnaryFunctorFilter<br />
<br />
= Member Variables =<br />
<br />
Filters should not use member variables to hold to their inputs or outputs.<br />
<br />
The inputs and outputs should be maintained by the methods<br />
<br />
SetInput(const InputImageType *input)<br />
{<br />
this->ProcessObject::SetNthInput( 0,const_cast< InputImageType * >( input ) );<br />
}<br />
<br />
<br />
GetInput( unsigned int idx ) <br />
{<br />
return static_cast< const TInputImage * >( this->ProcessObject::GetInput(idx) );<br />
}<br />
<br />
<br />
GetOutput()<br />
{<br />
if ( this->GetNumberOfOutputs() < 1 )<br />
{<br />
return 0;<br />
}<br />
<br />
return static_cast< TOutputImage * >( this->ProcessObject::GetOutput(0) );<br />
}<br />
<br />
<br />
In most cases, these methods are already provided by super classes. In particular by<br />
<br />
* itk::ImageSource<br />
* itk::ImageToImageFilter<br />
<br />
<br />
<br />
= Notes =<br />
<br />
<br />
{{ITK/Template/Footer}}</div>Nocnokneohttps://public.kitware.com/Wiki/index.php?title=VTK/Futures/Math_Library&diff=47073VTK/Futures/Math Library2012-05-14T17:29:52Z<p>Nocnokneo: /* Motivation */</p>
<hr />
<div>==Motivation==<br />
A [http://www.vtk.org/pipermail/vtk-developers/2010-January/006953.html recent discussion on the vtk-developers] mailing list (continued [http://www.vtk.org/pipermail/vtk-developers/2010-January/007196.html here]) described the need for a standard maths/vectors package for VTK.<br />
<br />
This page captures the motivation, requirements and evaluation of candidates.<br />
<br />
==Requirements==<br />
<br />
* Licensing requirements<br />
*Technical requirements<br />
* Performance requirement<br />
* Portability requirements<br />
* VTK-compatibility requirements<br />
* Other Requirements<br />
<br />
==Candidates==<br />
===[http://eigen.tuxfamily.org/index.php?title=Main_Page eigen2]===<br />
===[http://www.intel.com/cd/software/products/asmo-na/eng/307757.htm Intel Math Kernel Library]===<br />
===[http://www.amd.com/acml AMD's core math library]===<br />
===[http://www.csar.cfs.ac.uk/user_information/software/maths/goto.shtml GOTO BLAS]===<br />
===[http://math-atlas.sourceforge.net/ Automatically Tuned Linear Algebra Software (ATLAS)]===<br />
===[http://www.osl.iu.edu/research/mtl The Matrix Template Library]===<br />
<br />
==Evaluation==</div>Nocnokneohttps://public.kitware.com/Wiki/index.php?title=ITK/Coding_Style_Guide&diff=46995ITK/Coding Style Guide2012-05-03T19:44:58Z<p>Nocnokneo: /* C++ Code Style */</p>
<hr />
<div>= C++ Code Style =<br />
<br />
The document located [[media:ITKStyle.pdf|HERE]] describes ITK coding conventions. Developers should follow these conventions when submitting contributions.<br />
<br />
ITK Style Guide<br />
Insight Software Consortium<br />
<br />
== Purpose ==<br />
<br />
The following document is a description of the accepted coding style for the NLM Insight Segmentation<br />
and Registration Toolkit (ITK). Developers who wish to contribute code to ITK should read<br />
and adhere to the standards described here.<br />
<br />
== Document Overview ==<br />
This document is organized into the following sections.<br />
<br />
* System Overview & Philosophy | coding methodologies and motivation for the resulting style.<br />
* Copyright | the copyright header to be included in all files and other copyright issues.<br />
* File organization | how to organize source code; a guide to the ITK directory structure.<br />
* Naming conventions | patterns used to name classes, variables, template parameters, and instance variables.<br />
* Namespaces | the use of namespaces.<br />
* Code Layout and Indentation | accepted standards for arranging code including indentation style.<br />
* Doxygen Documentation System | basic Doxygen formatting instructions.<br />
* Using Standard Macros (itkMacro.h) | use of standard macros in header files.<br />
* Exception Handling | how to add exception handling to the system.<br />
* Documentation Style | a brief section describing the documentation philosophy adopted by the Insight consortium.<br />
<br />
This style guide is an evolving document.<br />
<br />
Please dialog with the ITK developers if you wish to add, modify, or delete the rules described in these guidelines.<br />
<br />
See:<br />
<br />
http://www.itk.org/ITK/help/mailing.html<br />
<br />
for more information about joining the ITK developers mailing list. This forum is one of the best venues in which to propose changes to these style guidelines.<br />
<br />
== Style Guidelines ==<br />
<br />
The following coding-style guidelines have been adopted by the ITK community. To a large extent<br />
these guidelines are a result of the fundamental architectural and implementation decisions made<br />
early in the project. For example, the decision was made to implement ITK with a C++ core using<br />
principles of generic programming, so the rules are oriented towards this style of implementation.<br />
Some guidelines are relatively arbitrary, such as indentation levels and style. However, an attempt<br />
was made to find coding styles consistent with accepted practices. The point is to adhere to a<br />
common style to assist developers and users of the future learn, use, maintain, and extend ITK.<br />
(See the ITK Requirements document for more information.)<br />
Please do your best to be a upstanding member of the ITK community. The rules described here<br />
have been developed with the community as a whole in mind. If you consistently violate these rules<br />
you will likely be harassed mercilessly, first privately and then publicly. If this does not result in<br />
correct code layout, your right to CVS write access (if you are developer and wish to contribute<br />
code) may be removed. Similarly, if you wish to contribute code and are not a developer, your code<br />
will not be accepted until the style is consistent with these guidelines.<br />
<br />
=== System Overview & Philosophy ===<br />
The following implementation strategies have been adopted by the ITK community. These directly<br />
and indirectly affect the resulting code style. Understanding these strategies motivate the reasons<br />
for many of the style guidelines described in this document.<br />
<br />
==== Implementation Language ====<br />
<br />
The core implementation language is C++. C++ was chosen for its flexibility, performance, and<br />
familiarity to consortium members. (Auxiliary, interpreted language bindings such as Tcl, Python,<br />
and/or Java are also planned. These are aimply (run-time interpreted) layers on the C++ code.)<br />
ITK uses the full spectrum of C++ features including const and volatile correctness, namespaces,<br />
partial template specialization, operator overloading, traits, and iterators.<br />
<br />
==== Generic Programming and the STL ====<br />
<br />
Compile-time binding using methods of generic programming and template instantiation is the<br />
preferred implementation style. This approach has demonstrated its ability to create efficient,<br />
<br />
exible code. Use of the STL (Standard Template Library) is encouraged. STL is typically used by<br />
a class, rather than as serving as a base class for derivation of ITK classes. Other STL influences<br />
are iterators and traits. ITK defines a large set of iterators; however, the ITK iterator style differs<br />
in many cases from STL because STL iterators follow a linear traversal model; ITK iterators are<br />
often designed for 2D, 3D, and even n-D traversal. Traits are used heavily be ITK. ITK naming<br />
conventions supersede STL naming conventions; this difference is useful in that it indicates to the<br />
developer something of the boundary between ITK and STL.<br />
<br />
==== Portability ====<br />
ITK is designed to compile on a set of target operating system/compiler combinations.<br />
<br />
These combinations include, but are not limited to:<br />
<br />
* Windows 9x/NT/2000/XP running<br />
** Microsoft Visual C++ version 7.1 to 10<br />
* Solaris with SunPro compiler <br />
* Linux running gcc<br />
* MacOSX running gcc<br />
* Intel compiler on Windows and Linux<br />
<br />
For a full list of the compilers supported please see:<br />
<br />
* [[ITK_Release_4/Modern C++|Modern C++]]<br />
<br />
==== Multi-Layer Architecture ====<br />
ITK is designed with a multi-layer architecture in mind. That is, three layers, a templated layer, a<br />
run-time layer, and an application layer. The templated (or generic) layer is written in C++ and<br />
requires significant programming skills and domain knowledge. The run-time layer is generated<br />
automatically using the CableSwig wrapping system to produce language bindings to Tcl, Python,<br />
and Java. The interpreted layer is easier to use than the templated layer, and can be used for<br />
prototyping and smaller-sized application development. Finally, the application layer is not directly<br />
addressed by ITK other than providing simple examples of applications.<br />
<br />
==== CMake Build Environment ====<br />
The ITK build environment is CMake. CMake is an open-source, advanced cross-platform build<br />
system that enables developers to write simple \makefiles" (named CMakeLists.txt) that are processed<br />
to generated native build tools for a particular operating system/compiler combinations.<br />
See the CMake web pages at http://www.cmake.org for more information.<br />
<br />
==== Doxygen Documentation System ====<br />
<br />
The Doxygen open-source system is used to generate on-line documentation. Doxygen requires the<br />
embedding of simple comments in the code which is in turn extracted and formatted into documentation.<br />
<br />
For more information about Doxygen, please see<br />
<br />
http://www.stack.nl/dimitri/doxygen/<br />
<br />
==== vnl Math Library ====<br />
ITK has adopted the vnl math library. Vnl is a portion of the vxl image understanding environment.<br />
See http://www.robots.ox.ac.uk/ vxl/ for more information about vxl and vnl.<br />
<br />
==== Reference Counting ====<br />
<br />
ITK has adopted reference counting via so-called "smart pointers" to manage object references.<br />
While alternative approaches such as automatic garbage collection were considered, their overhead<br />
due to memory requirements, performance, and lack of control as to when to delete memory, precluded<br />
these methods. Smart pointers manage the reference to objects, automatically incrementing<br />
and deleting an instance's reference count, deleting the object when the count goes to zero.<br />
These are the most important factors influencing the coding style found in Insight. Now we will<br />
look at the details.<br />
<br />
=== Copyright ===<br />
<br />
ITK has adopted a standard copyright. This copyright should be placed at the head of every source<br />
code file. The current copyright header and license reads as follows:<br />
<br />
<pre><nowiki><br />
/*========================================================================= <br />
* <br />
* Copyright Insight Software Consortium <br />
* <br />
* Licensed under the Apache License, Version 2.0 (the "License"); <br />
* you may not use this file except in compliance with the License. <br />
* You may obtain a copy of the License at <br />
* <br />
* http://www.apache.org/licenses/LICENSE-2.0.txt <br />
* <br />
* Unless required by applicable law or agreed to in writing, software <br />
* distributed under the License is distributed on an "AS IS" BASIS, <br />
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br />
* See the License for the specific language governing permissions and <br />
* limitations under the License. <br />
* <br />
*=========================================================================*/<br />
</nowiki></pre><br />
<br />
[[ITK Copyright Header|Copyright Header]]<br />
<br />
=== File Organization ===<br />
<br />
Classes are created and (usually) organized into a single class per file set. A file set consists of .h<br />
header file, .cxx implementation file, and/or a .hxx templated implementation file. Helper classes<br />
may also be defined in the file set, typically these are not visible to the system at large, or placed<br />
into a special namespace.<br />
<br />
Source files must be placed in the correct directory for logical consistency with the rest of the<br />
system, and to avoid cyclic dependencies. Currently the ITK source directory structure is found in<br />
ITK/Modules and consists of the following subdirectories:<br />
<br />
* Bridge<br />
* Core<br />
* External<br />
* Filtering<br />
* GPU<br />
* IO<br />
* Nonunit<br />
* Numerics<br />
* Registration<br />
* Segmentation<br />
* ThirdParty<br />
<br />
Each one of these directories represent a Group of Modules.<br />
<br />
Please discuss with the ITK Developers about the best Module to place your new code.<br />
<br />
For a full list of Modules, please see:<br />
<br />
http://www.itk.org/Doxygen/html/modules.html<br />
<br />
=== Naming Conventions ===<br />
<br />
In general, <br />
<br />
* Names are constructed by using case change to indicate separate words, as in TimeStamp<br />
(versus Time Stamp).<br />
* Underscores are not used.<br />
* Variable names are chosen carefully with the intention to convey the meaning behind the code.<br />
* Names are generally spelled out; use of abbreviations is discouraged. (Abbreviation are allowable when in common use, and should be in<br />
uppercase as in RGB.) While this does result in long names, it self-documents the code.<br />
* If you learn how to use name completion in your editor (e.g.,Vim, Emacs), this inconvenience can be minimized.<br />
<br />
Depending on whether the name is a<br />
<br />
* class<br />
* file<br />
* variable<br />
* or other name<br />
<br />
variations on this theme result as explained in the following subsections.<br />
<br />
==== Naming Classes ====<br />
<br />
* Classes are named beginning with a capital letter.<br />
* Classes are placed in the appropriate namespace, typically itk:: (see namespaces below).<br />
* Classes are named according to the following general rule:<br />
class name = <algorithm><input><concept><br />
* In this formula, the name of the algorithm or process (possibly with an associated adjective or<br />
adverb) comes first, followed by an input type (if the class is a filter), and completed by a concept<br />
name.<br />
* A concept is an informal classification describing what a class does. There are many<br />
concepts, here are a few of them.<br />
<br />
The more common or important concepts are underlined.<br />
<br />
* '''Accessor''' Access and convert between types.<br />
* '''Adaptor''' Provide access to a portion of a complex pixel type.<br />
* '''Boundary''' The boundary of a cell.<br />
* '''Calculator''' Compute information.<br />
* '''Classifier''' Classify a pixel.<br />
* '''Container''' A container of objects such as points or cells.<br />
* '''Estimator''' Estimate a value or condition.<br />
* '''Factory''' Object factories are used to create instances.<br />
* '''Filter''' A class that participates in the data processing pipeline. Filters typically take one or more<br />
* '''inputs''' and produce one or more outputs.<br />
* '''Function''' Evaluate a function at a given position.<br />
* '''Identifier''' A unique id for accessing points, cells, or other entities.<br />
* '''Interface''' Classes that specify an abstract interface.<br />
* '''Interpolator''' Interpolate data values, for example at non-pixel values.<br />
* '''Iterator''' Traverse data in various ways (e.g., forward, backward, within a region, etc.)<br />
* '''Mapper''' Transform data from one form into another.<br />
* '''Metric''' Compute similarity between two objects.<br />
* '''Operator''' A class that applies a user-specified function to a region.<br />
* '''Optimizer''' A class that performs numerical optimization.<br />
* '''Pointer''' A smart pointer to an instance of a class. Almost all instance in ITK are referred to via smart pointers.<br />
* '''Reader''' A class that reads a single data object (e.g., image or mesh).<br />
* '''Reference''' A type that refers to another object.<br />
* '''Region''' A subset of a data object, such as an image region.<br />
* '''Source''' A filter that initiates the data processing pipeline such as a reader or a procedural data<br />
* '''generator'''.<br />
* '''Threader''' A class that manages multi-threading.<br />
* '''Traits''' A collection of template parameters used to control the instantiation of other classes.<br />
* '''Transform''' Various types of transformations including affine, procedural, and so on.<br />
* '''Writer''' A filter that terminates the data processing pipeline by writing data to disk or to a communicationsport.<br />
<br />
<br />
The naming of classes is an art form; please review existing names to catch the spirit of the naming<br />
convention.<br />
<br />
Example names include:<br />
<br />
* ShrinkImageFilter<br />
* TriangleCell<br />
* ScalarImageRegionIterator<br />
* NeighborhoodIterator<br />
* MapContainer<br />
* DefaultImageTraits<br />
* BackwardDifferenceOperator<br />
<br />
==== Naming Files ====<br />
<br />
* Files should have the same name as the class, with an "itk" prepended.<br />
* Header files are named .h, while implementation files are named either .cxx or .hxx, depending on whether they are implementations of templated classes.<br />
** For example, the class itk::Image <br />
*** is declared in the file itkImage.h and<br />
*** is defined in the file itkImage.hxx (because Image is templated).<br />
** The class itk::Object<br />
*** is declared in the file itkObject.h<br />
*** and is defined in the file itkObject.cxx<br />
<br />
==== Naming Methods and Functions ====<br />
Global functions and class methods, either static or class members, are named beginning with<br />
a capital letter. The biggest challenge when naming methods and functions is to be consistent<br />
with existing names. For example, given the choice between ComputeBoundingBox() and<br />
CalculateBoundingBox() (CalcBoundingBox() is not allowed because it is not spelled out), the<br />
choice is ComputeBoundingBox() because \Compute" is used elsewhere in the system for in similar<br />
settings. (The concepts described previously should be used whenever possible.)<br />
When referring to class methods in code, an explicit this-> pointer should be used, as in this->ComputeBoundingBox().<br />
The use of the explicit this-> pointer helps clarify exactly which method, and where it originates,<br />
is being invoked. Similarly the \::" global namespace should be used when referring to a global<br />
function.<br />
<br />
==== Naming Class Data Members ====<br />
<br />
Class data members are prepended with m as in m Size. This clearly indicates the origin of data<br />
members, and differentiates them from all other variables.<br />
<br />
==== Naming Local Variables ====<br />
Local variables begin in lowercase. There is more <br />
exibility in the naming of local variables; please<br />
remember that others will study, maintain, fix, and extend your code. Any bread crumbs that<br />
you can drop in the way of explanatory variable names and comments will go a long way towards<br />
helping other developers.<br />
<br />
==== Naming Template Parameters ====<br />
Template parameters follow the usual rules with naming except that they should start with either<br />
the capital letter T or V. Type parameters begin with the letter T while value template parameters<br />
begin with the letter V.<br />
<br />
==== Naming Typedefs ====<br />
Typedefs are absolutely essential in generic programming. They significantly improve the readibility<br />
of code, and facilitate the declaration of complex syntactic combinations. Unfortuneatly, creation<br />
of typedefs is tantamount to creating another programming language. Hence typedefs must be used<br />
in a consistent fashion.<br />
The general rule for typedef names is that they end in the word Type. For example<br />
typedef TPixel PixelType;<br />
However, there are many exceptions to this rule that recognize that ITK has several important<br />
concepts that are expressed partially in the names used to implement the concept. An iterator is a<br />
concept, as is a container or pointer. These concepts are used in preference to Type at the end of<br />
a typedef as appropriate. For example<br />
ITK Style Guide 9<br />
typedef typename ImageTraits::PixelContainer PixelContainer;<br />
Here Container is a concept used in place of Type.<br />
ITK currently identifies the following concepts used when naming typedefs.<br />
* Self as in \typedef Image Self;". All classes should define this typedef.<br />
* Superclass as in typedef ImageBase<VImageDimension> Superclass;. All classes should<br />
define the Superclass typedef.<br />
* Pointer as in a smart pointer to an object as in typedef SmartPointer<Self> Pointer;<br />
* Container is a type of container class.<br />
* Iterator an iterator over some container class.<br />
* Identifier or id such as a point or cell id.<br />
<br />
==== Using Underscores ====<br />
Don't use them. The only exception is when defining preprocessor variables and macros (which are<br />
discouraged). In this case, underscores are allowed to separate words.<br />
<br />
==== Preprocessor Directives ====<br />
<br />
* Some of the worst code contains many preprocessor directives and macros. Do not use them except in a very limited sense (to support minor differences in compilers or operating systems). <br />
* If a class makes extensive use of preprocessor directives, it is a candidate for separation into multiple sub-classes.<br />
<br />
==== Namespaces ====<br />
<br />
All classes should be placed in the itk:: namespace. Additional sub-namespaces are being designed to support special functionality.<br />
<br />
Please see current documentation to determine if there is a subnamespace is relevant to your situation. Normally sub-namespaces are used for helper ITK classes.<br />
<br />
==== Const Correctness ====<br />
<br />
Const correctness is important. Please use it as appropriate to your class or method.<br />
<br />
==== Code Layout and Indentation ====<br />
<br />
The following are the accepted ITK code layout rules and indentation style. After reading this section, you may wish to visit many of the source files found in ITK. This will help crystallize the rules described here.<br />
<br />
==== General Layout ====<br />
<br />
* Each line of code should take no more than 100 characters.<br />
* Break the code across multiple lines as necessary.<br />
* Use lots of whitespace to separate logical blocks of code, intermixed with comments.<br />
* To a large extent the structure of code directly expresses its implementation.<br />
* The appropriate indentation level is '''two spaces''' for each level of indentation.<br />
* '''DO NOT USE TABS.'''<br />
** Set up your editor to insert spaces. Using tabs may look good in your editor but will wreak havoc in others.<br />
* The declaration of variables within classes, methods, and functions should be one declaration per line.<br />
<br />
<source lang="cpp"><br />
int i;<br />
int j;<br />
char* stringname;<br />
</source><br />
<br />
==== Class Layout ====<br />
<br />
Classes are defined using the following guidelines.<br />
* Begin with #include guards.<br />
* Follow with the necessary includes. Include only what is necessary to avoid dependency<br />
problems.<br />
* Place the class in the correct namespace.<br />
* Public methods come first.<br />
* Protected methods follow.<br />
* Private members come last.<br />
* Public data members are forbidden.<br />
* Templated classes require a special preprocessor directive to control the manual instantiation<br />
of templates. See the example below and look for ITK MANUAL INSTANTIATION.)<br />
The class layout looks something like this:<br />
<br />
<source lang="cpp"><br />
#ifndef __itkImage_h<br />
#define __itkImage_h<br />
#include "itkImageBase.h"<br />
#include "itkPixelTraits.h"<br />
#include "itkDefaultImageTraits.h"<br />
#include "itkDefaultDataAccessor.h"<br />
namespace itk<br />
{<br />
ITK Style Guide 11<br />
template <class TPixel, unsigned int VImageDimension=2,<br />
class TImageTraits=DefaultImageTraits< TPixel, VImageDimension > ><br />
class ITK_EXPORT Image : public ImageBase<VImageDimension><br />
{<br />
public:<br />
....stuff...<br />
protected:<br />
....stuff...<br />
private:<br />
....stuff...<br />
};<br />
}//end of namespace<br />
#ifndef ITK_MANUAL_INSTANTIATION<br />
#include "itkImage.hxx"<br />
#endif<br />
#endif //end include guard<br />
</source><br />
<br />
==== Method Definition ====<br />
<br />
* Methods are defined across multiple lines. This is to accommodate the extremely long definitions possible when using templates.<br />
* The starting and ending brace should be in column one. For example:<br />
<br />
<source lang="cpp"><br />
template<class TPixel, unsigned int VImageDimension, class TImageTraits><br />
const double *<br />
Image<TPixel, VImageDimension, TImageTraits><br />
::GetSpacing() const<br />
{<br />
...<br />
}<br />
</source><br />
<br />
* The first line is the template declaration.<br />
* The second line is the method return type.<br />
* The third line is the class qualifier.<br />
* And the fourth line in the example above is the name of the method.<br />
<br />
=== Use of Braces ===<br />
<br />
* Braces must be used to delimit the scope of an if, for, while, switch, or other control structure.<br />
* Braces are placed on a line by themselves:<br />
<br />
<source lang="cpp"><br />
for (i=0; i<3; i++)<br />
{<br />
...<br />
}<br />
</source><br />
<br />
<br />
or when using an if:<br />
<br />
<source lang="cpp"><br />
if ( condition )<br />
{<br />
...<br />
}<br />
else if ( other condition )<br />
{<br />
...<br />
}<br />
else<br />
{<br />
....<br />
}<br />
</source><br />
<br />
<br />
=== Doxygen Documentation System ===<br />
<br />
* Doxygen is an open-source, powerful system for automatically generating documentation from source code.<br />
* To use Doxygen effectively, the developer must insert comments, delimited in a special way, that Doxygen extracts to produce the documentation. While there are a large number of options to Doxygen, developers at a minimum should insert the following Doxygen commands.<br />
<br />
See more at<br />
<br />
http://www.stack.nl/dimitri/doxygen/index.html<br />
<br />
==== Documenting a Class ====<br />
<br />
* Classes should be documented using the '''class''' and '''brief''' Doxygen commands, followed by the detailed class description:<br />
<br />
<source lang="cpp"><br />
/** \class Object<br />
* \brief Base class for most itk classes.<br />
*<br />
* Object is the second-highest level base class for most itk objects.<br />
* It extends the base object functionality of LightObject by<br />
* implementing debug flags/methods and modification time tracking.<br />
*/<br />
</source><br />
<br />
==== Documenting a Method ====<br />
<br />
Methods should be documented using the following comment block style as shown in the following<br />
example. Make sure you use correct English and complete, grammatically correct sentences.<br />
<br />
<br />
<source lang="cpp"><br />
/** Access a pixel at a particular index location.<br />
* This version can be an lvalue. */<br />
TPixel & operator[](const IndexType &index)<br />
{ return this->GetPixel(index); }<br />
</source><br />
<br />
The key here is that the comment starts with /**, each subsequent line has an aligned *, and the<br />
comment block terminates with a */.<br />
<br />
<br />
=== Using Standard Macros (itkMacro.h) ===<br />
<br />
* There are several macros defined in the file itkMacro.h.<br />
* These macros should be used because they perform several important operations, that if not done correctly can cause serious, hard to debug problems in the system.<br />
** These operations are:<br />
*** Object modified time is properly managed.<br />
*** Debug information is printed.<br />
*** Reference counting is handled properly.<br />
<br />
Some of the more important object macros are as follows.<br />
<br />
* itkNewMacro(T) Creates the static class method New(void) that interacts with the object factory to instantiate objects. The method returns a SmartPointer<T> properly reference counted.<br />
* itkDebugMacro(x) If debug is set on a subclass of itk::Object, prints debug information to the appropriate output stream.<br />
* itkSetMacro(name,type) Creates a method SetName() that takes argument type type.<br />
* itkGetMacro(name,type) Creates a method GetName() that returns a non-const value of type type.<br />
* itkGetConstMacro(name,type) Creates a method GetName() that returns a const value of type type.<br />
* itkSetStringMacro(name) Creates a method SetName() that takes argument type const char*.<br />
* itkGetStringMacro(name) Creates a method GetName() that returns argument type const char*.<br />
* itkBooleanMacro(name) Creates two methods named NameOn and NameOff that sets true/false boolean values.<br />
* itkSetObjectMacro(name,type) Creates a method SetName() that takes argument type type *.<br />
* itkGetObjectMacro(name,type) Creates a method named GetName() that returns a smart pointer to a type type.<br />
* itkSetConstObjectMacro(name,type) Creates a method SetName() that takes argument type const type *.<br />
* itkGetConstObjectMacro(name,type) Creates a method named GetName() that returns a const smart pointer to a type type.<br />
<br />
Please review this file and become familiar with these macros.<br />
<br />
=== Exception Handling ===<br />
<br />
Indicate that methods throw exceptions in the method declaration as in:<br />
<br />
<source lang="cpp"><br />
const float* foo() const throws itk<br />
</source><br />
<br />
=== Documentation Style ===<br />
<br />
The Insight consortium has adopted the following guidelines for producing supplemental documentation (documentation not produced by Doxygen).<br />
<br />
* The common denominator for documentation is either PDF or HTML. All documents in the system should be available in these formats, even if they are mastered by another system.<br />
* Presentations are acceptable in Microsoft PowerPoint format.<br />
* Administrative and planning documents are acceptable in Microsoft Word format (either .doc or .rtf).<br />
* Larger documents, such as the user's or developer's guide, are written in LATEX.<br />
<br />
== CMake Style ==<br />
<br />
A proposal style guide for CMake variables is presented [[ITK_CMake_Style|HERE]].<br />
<br />
{{ITK/Template/Footer}}</div>Nocnokneohttps://public.kitware.com/Wiki/index.php?title=User:Nocnokneo&diff=42980User:Nocnokneo2011-09-09T14:58:37Z<p>Nocnokneo: link to homepage</p>
<hr />
<div>= Taylor Braun-Jones =<br />
<br />
http://taylor.braun-jones.org</div>Nocnokneohttps://public.kitware.com/Wiki/index.php?title=VTK/Tutorials/SmartPointers&diff=38449VTK/Tutorials/SmartPointers2011-03-16T19:38:36Z<p>Nocnokneo: /* Idea */ grammar error</p>
<hr />
<div>==Idea==<br />
The idea behind smart pointers is reference counting. If the object goes out of scope and it is not being used anywhere else, it will be deleted automatically. This is an important part of writing exception-safe code. With the proper use of smart pointers, you should never see an explicit Delete invocation in your code. Pretty 'smart', eh?<br />
<br />
Note: vtkSmartPointer in combination with the internal reference counting of vtkObject reproduces much of the functionality of the std::tr1::shared_ptr template class introduced in the C++ Standard's Library Extensions Technical Report 1 (known as TR1). (This class first appeared as part of the [http://boost.org Boost library].) If you're familiar with shared_ptr, then you already know most of how to use vtkSmartPointer. The principle difference is that, in VTK, the reference count is stored in the object, not the smart pointer. A vtkObject "owns itself", and the special vtkSmartPointer<>::New() method creates an object and smart pointer in one step, with the pointer holding the initial ownership of the object.<br />
<br />
==Usage==<br />
===Creating an Object with a Smart Pointer===<br />
One way to create a VTK object is<br />
<source lang="cpp"><br />
vtkObject* MyObject = vtkObject::New();<br />
</source><br />
<br />
This method, however, can (and likely will) lead to memory management issues at some point or another. You must manually delete the object<br />
<source lang="cpp"><br />
MyObject->Delete();<br />
</source><br />
<br />
or you will have a memory leak. VTK's solution to this ever-annoying problem is the smart pointer. To use it, you must<br />
<br />
<source lang="cpp"><br />
#include <vtkSmartPointer.h><br />
</source><br />
<br />
Then you can create an object as follows:<br />
<source lang="cpp"><br />
vtkSmartPointer<vtkObject> MyObject = vtkSmartPointer<vtkObject>::New();<br />
</source><br />
<br />
Note the special syntax on the right of the assignment. One almost never wants to assign a raw object pointer to a smart pointer, as is done here:<br />
<source lang="cpp"><br />
vtkSmartPointer<vtkObject> MyObject = vtkObject::New();<br />
</source><br />
<br />
This is almost always a coding error, because the reference count is incremented, requiring an explicit Delete later.<br />
<br />
=== Putting an Existing Object into a Smart Pointer ===<br />
<br />
You may need to wrap a raw pointer because you need to use a constructor that takes arguments. In this situation, use the Take method. This passes the object's self-ownership to the smart pointer:<br />
<source lang="cpp"><br />
class MySpecialClass : public vtkObject { /* ... */ };<br />
MySpecialClass* MyObjectRaw = new MyObject(arguments);<br />
vtkSmartPointer<MySpecialClass> MyObject;<br />
MyObject.Take(MyObjectRaw);<br />
</source><br />
<br />
Because MyObject now owns the object, there is no need to invoke MyObjectRaw->Delete().<br />
<br />
=== Getting an Object with a Smart Pointer ===<br />
When not allocating memory for an object, you can still use smart pointers. Take this simple example:<br />
<source lang="cpp"><br />
vtkSmartPointer<vtkXMLPolyDataReader> Reader = vtkSmartPointer<vtkXMLPolyDataReader>::New();<br />
vtkPolyData* pd = Reader->GetOutput();<br />
</source><br />
vs<br />
<source lang="cpp"><br />
vtkSmartPointer<vtkPolyData> pd = Reader->GetOutput();<br />
</source><br />
<br />
In the first case, when the reader object goes out of scope, the data is deleted. In the second case, by using a smart pointer we have incremented the data's reference count by 1, so the data will not be deleted until the reader AND the polydata object go out of scope.<br />
<br />
=== Returning a Smart Pointer ===<br />
'''Correct'''<br />
<br />
You should define a function like this:<br />
<source lang="cpp"><br />
vtkSmartPointer<vtkPolyData> MyFunction()<br />
{<br />
vtkSmartPointer<vtkPolyData> myObject = vtkSmartPointer<vtkPolyData>::New();<br />
return myObject;<br />
}<br />
</source><br />
<br />
And call the function using:<br />
<source lang="cpp"><br />
vtkSmartPointer<vtkPolyData> MyPolydata = MyFunction();<br />
</source><br />
<br />
The smart pointer in the function is copied to the smart pointer in the caller, so the reference count remains unchanged and the associated object is not deleted.<br />
<br />
'''Incorrect'''<br />
<br />
<source lang="cpp"><br />
vtkPolyData* MyFunction()<br />
{<br />
vtkSmartPointer<vtkPolyData> MyObject = vtkSmartPointer<vtkPolyData>::New();<br />
return MyObject;<br />
}<br />
<br />
vtkPolyData* MyPolydata = MyFunction();<br />
</source><br />
<br />
In this case, the smart pointer is converted to a raw pointer before being returned to the caller. As the function exits, the smart pointer's reference count goes to zero and the actual object is deleted, leaving the raw pointer dangling, pointing at freed memory.<br />
<br />
=== Using Smart Pointers as Class Member Variables ===<br />
Smart pointers make class destructors simple, by automatically releasing ownership of shared objects.<br />
<br />
Declare the pointer like this:<br />
<source lang="cpp"><br />
class MyClass<br />
{<br />
vtkSmartPointer<vtkFloatArray> Distances;<br />
};<br />
</source><br />
<br />
You can initialize the smart pointer in your constructor using an initializer:<br />
<source lang="cpp"><br />
MyClass::MyClass()<br />
: Distances(vtkSmartPointer<vtkFloatArray>::New())<br />
{}<br />
</source><br />
<br />
Or you can initialize it with an assignment statement:<br />
<source lang="cpp"><br />
MyClass::MyClass()<br />
{<br />
Distances = vtkSmartPointer<vtkFloatArray>::New();<br />
}<br />
</source><br />
<br />
There is no need to explicitly Delete the object in your class destructor. By using smart pointers in your classes, your destructors become much simpler. You may find that you don't have to write a destructor at all, as the default destructor will Delete all your objects through the magic of the smart pointer.<br />
<br />
==Pitfalls==<br />
* If you create an object and then change where it is pointing, the reference count will be incorrect. e.g.<br />
<source lang="cpp"><br />
vtkSmartPointer<vtkPolyData> Polydata = vtkSmartPointer<vtkPolyData>::New();<br />
Polydata = Reader->GetOutput();<br />
</source><br />
In this case, memory is allocated for Polydata, but then we change Polydata to point to the output of Reader rather than the memory we just allocated. Instead, we should have done simply:<br />
<source lang="cpp"><br />
vtkPolyData* Polydata = Reader->GetOutput();<br />
</source><br />
<br />
It was not necessary to use a smart pointer because we did not actually create any new objects.<br />
<br />
==Example==<br />
Here is an example of equivalent operations with and without smart pointers:<br />
<br />
===SmartPointers.cpp===<br />
<source lang="cpp"><br />
#include <vtkFloatArray.h><br />
#include <vtkSmartPointer.h><br />
<br />
void WithSmartPointers();<br />
void WithoutSmartPointers();<br />
<br />
int main(int argc, char *argv[])<br />
{<br />
WithSmartPointers();<br />
WithoutSmartPointers();<br />
<br />
return 0;<br />
}<br />
<br />
void WithSmartPointers()<br />
{<br />
vtkSmartPointer<vtkFloatArray> Distances = vtkSmartPointer<vtkFloatArray>::New();<br />
}<br />
<br />
void WithoutSmartPointers()<br />
{<br />
vtkFloatArray* Distances = vtkFloatArray::New();<br />
Distances->Delete();<br />
}<br />
<br />
</source><br />
<br />
===CMakeLists.txt===<br />
<source lang="cmake"><br />
cmake_minimum_required(VERSION 2.6)<br />
<br />
PROJECT(SmartPointers)<br />
<br />
FIND_PACKAGE(VTK REQUIRED)<br />
INCLUDE(${VTK_USE_FILE})<br />
<br />
ADD_EXECUTABLE(SmartPointers SmartPointers.cpp)<br />
TARGET_LINK_LIBRARIES(SmartPointers vtkHybrid)<br />
<br />
</source></div>Nocnokneo