code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
codeception Memcache Memcache
========
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-memcache
```
Alternatively, you can enable `Memcache` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Connects to [memcached](https://www.memcached.org/) using either *Memcache* or *Memcached* extension.
Performs a cleanup by flushing all values after each test run.
Status
------
* Maintainer: **davert**
* Stability: **beta**
* Contact: [email protected]
Configuration
-------------
* **`host`** (`string`, default `'localhost'`) - The memcached host
* **`port`** (`int`, default `11211`) - The memcached port
### Example (`unit.suite.yml`)
```
modules:
- Memcache:
host: 'localhost'
port: 11211
```
Be sure you don’t use the production server to connect.
Public Properties
-----------------
* **memcache** - instance of *Memcache* or *Memcached* object
Actions
-------
### clearMemcache
Flushes all Memcached data.
### dontSeeInMemcached
Checks item in Memcached doesn’t exist or is the same as expected.
Examples:
```
<?php
// With only one argument, only checks the key does not exist
$I->dontSeeInMemcached('users_count');
// Checks a 'users_count' exists does not exist or its value is not the one provided
$I->dontSeeInMemcached('users_count', 200);
?>
```
* `param` $key
* `param` $value
### grabValueFromMemcached
Grabs value from memcached by key.
Example:
```
<?php
$users_count = $I->grabValueFromMemcached('users_count');
?>
```
* `param` $key
* `return array|string`
### haveInMemcached
Stores an item `$value` with `$key` on the Memcached server.
* `param string` $key
* `param mixed` $value
* `param int` $expiration
### seeInMemcached
Checks item in Memcached exists and the same as expected.
Examples:
```
<?php
// With only one argument, only checks the key exists
$I->seeInMemcached('users_count');
// Checks a 'users_count' exists and has the value 200
$I->seeInMemcached('users_count', 200);
?>
```
* `param` $key
* `param` $value
codeception SOAP SOAP
====
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-soap
```
Alternatively, you can enable `SOAP` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Module for testing SOAP WSDL web services. Send requests and check if response matches the pattern.
This module can be used either with frameworks or PHPBrowser. It tries to guess the framework is is attached to. If a endpoint is a full url then it uses PHPBrowser.
### Using Inside Framework
Please note, that PHP SoapServer::handle method sends additional headers. This may trigger warning: “Cannot modify header information” If you use PHP SoapServer with framework, try to block call to this method in testing environment.
Status
------
* Maintainer: **davert**
* Stability: **stable**
* Contact: [email protected]
Configuration
-------------
* endpoint *required* - soap wsdl endpoint
* SOAPAction - replace SOAPAction HTTP header (Set to ‘’ to SOAP 1.2)
Public Properties
-----------------
* xmlRequest - last SOAP request (DOMDocument)
* xmlResponse - last SOAP response (DOMDocument)
Actions
-------
### dontSeeSoapResponseContainsStructure
Opposite to `seeSoapResponseContainsStructure`
* `param` $xml
### dontSeeSoapResponseContainsXPath
Checks XML response doesn’t contain XPath locator
```
<?php
$I->dontSeeSoapResponseContainsXPath('//root/user[@id=1]');
?>
```
* `param` $xpath
### dontSeeSoapResponseEquals
Checks XML response equals provided XML. Comparison is done by canonicalizing both xml`s.
Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
* `param` $xml
### dontSeeSoapResponseIncludes
Checks XML response does not include provided XML. Comparison is done by canonicalizing both xml`s. Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
* `param` $xml
### grabAttributeFrom
Finds and returns attribute of element. Element is matched by either CSS or XPath
* `Available since` 1.1
* `param` $cssOrXPath
* `param` $attribute
* `return string`
### grabTextContentFrom
Finds and returns text contents of element. Element is matched by either CSS or XPath
* `Available since` 1.1
* `param` $cssOrXPath
* `return string`
### haveSoapHeader
Prepare SOAP header. Receives header name and parameters as array.
Example:
```
<?php
$I->haveSoapHeader('AuthHeader', array('username' => 'davert', 'password' => '123345'));
```
Will produce header:
```
<soapenv:Header>
<SessionHeader>
<AuthHeader>
<username>davert</username>
<password>12345</password>
</AuthHeader>
</soapenv:Header>
```
* `param` $header
* `param array` $params
### seeSoapResponseCodeIs
Checks response code from server.
* `param` $code
### seeSoapResponseContainsStructure
Checks XML response contains provided structure. Response elements will be compared with XML provided. Only nodeNames are checked to see elements match.
Example:
```
<?php
$I->seeSoapResponseContainsStructure("<query><name></name></query>");
?>
```
Use this method to check XML of valid structure is returned. This method does not use schema for validation. This method does not require path from root to match the structure.
* `param` $xml
### seeSoapResponseContainsXPath
Checks XML response with XPath locator
```
<?php
$I->seeSoapResponseContainsXPath('//root/user[@id=1]');
?>
```
* `param` $xpath
### seeSoapResponseEquals
Checks XML response equals provided XML. Comparison is done by canonicalizing both xml`s.
Parameters can be passed either as DOMDocument, DOMNode, XML string, or array (if no attributes).
Example:
```
<?php
$I->seeSoapResponseEquals("<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope><SOAP-ENV:Body><result>1</result></SOAP-ENV:Envelope>");
$dom = new \DOMDocument();
$dom->load($file);
$I->seeSoapRequestIncludes($dom);
```
* `param` $xml
### seeSoapResponseIncludes
Checks XML response includes provided XML. Comparison is done by canonicalizing both xml`s. Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
Example:
```
<?php
$I->seeSoapResponseIncludes("<result>1</result>");
$I->seeSoapRequestIncludes(\Codeception\Utils\Soap::response()->result->val(1));
$dom = new \DDOMDocument();
$dom->load('template.xml');
$I->seeSoapRequestIncludes($dom);
?>
```
* `param` $xml
### sendSoapRequest
Submits request to endpoint.
Requires of api function name and parameters. Parameters can be passed either as DOMDocument, DOMNode, XML string, or array (if no attributes).
You are allowed to execute as much requests as you need inside test.
Example:
```
$I->sendSoapRequest('UpdateUser', '<user><id>1</id><name>notdavert</name></user>');
$I->sendSoapRequest('UpdateUser', \Codeception\Utils\Soap::request()->user
->id->val(1)->parent()
->name->val('notdavert');
```
* `param` $request
* `param` $body
codeception Queue Queue
=====
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-queue
```
Alternatively, you can enable `Queue` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Works with Queue servers.
Testing with a selection of remote/local queueing services, including Amazon’s SQS service Iron.io service and beanstalkd service.
Supported and tested queue types are:
* [Iron.io](http://iron.io/)
* [Beanstalkd](https://kr.github.io/beanstalkd/)
* [Amazon SQS](https://aws.amazon.com/sqs/)
The following dependencies are needed for the listed queue servers:
* Beanstalkd: pda/pheanstalk ~3.0
* Amazon SQS: aws/aws-sdk-php
* IronMQ: iron-io/iron\_mq
Status
------
* Stability:
+ Iron.io: **stable**
+ Beanstalkd: **stable**
+ Amazon SQS: **stable**
Config
------
The configuration settings depending on which queueing service is being used, all the options are listed here. Refer to the configuration examples below to identify the configuration options required for your chosen service.
* type - type of queueing server (defaults to beanstalkd).
* host - hostname/ip address of the queue server or the host for the iron.io when using iron.io service.
* port: 11300 - port number for the queue server.
* timeout: 90 - timeout settings for connecting the queue server.
* token - Iron.io access token.
* project - Iron.io project ID.
* key - AWS access key ID.
* version - AWS version (e.g. latest)
* endpoint - The full URI of the webservice. This is only required when connecting to a custom endpoint (e.g., a local version of SQS).
* secret - AWS secret access key. Warning: Hard-coding your credentials can be dangerous, because it is easy to accidentally commit your credentials into an SCM repository, potentially exposing your credentials to more people than intended. It can also make it difficult to rotate credentials in the future.
* profile - AWS credential profile - it should be located in ~/.aws/credentials file - eg: [default] aws\_access\_key\_id = YOUR\_AWS\_ACCESS\_KEY\_ID aws\_secret\_access\_key = YOUR\_AWS\_SECRET\_ACCESS\_KEY [project1] aws\_access\_key\_id = YOUR\_AWS\_ACCESS\_KEY\_ID aws\_secret\_access\_key = YOUR\_AWS\_SECRET\_ACCESS\_KEY - Note: Using IAM roles is the preferred technique for providing credentials to applications running on Amazon EC2 http://docs.aws.amazon.com/aws-sdk-php/v3/guide/guide/credentials.html?highlight=credentials
* region - A region parameter is also required for AWS, refer to the AWS documentation for possible values list.
### Example
##### Example (beanstalkd)
`modules:
enabled: [Queue]
config:
Queue:
type: 'beanstalkd'
host: '127.0.0.1'
port: 11300
timeout: 120` ##### Example (Iron.io)
`modules:
enabled: [Queue]
config:
Queue:
'type': 'iron',
'host': 'mq-aws-us-east-1.iron.io',
'token': 'your-token',
'project': 'your-project-id'` ##### Example (AWS SQS)
`modules:
enabled: [Queue]
config:
Queue:
'type': 'aws',
'key': 'your-public-key',
'secret': 'your-secret-key',
'region': 'us-west-2'` ##### Example AWS SQS using profile credentials
`modules:
enabled: [Queue]
config:
Queue:
'type': 'aws',
'profile': 'project1', //see documentation
'region': 'us-west-2'` ##### Example AWS SQS running on Amazon EC2 instance
`modules:
enabled: [Queue]
config:
Queue:
'type': 'aws',
'region': 'us-west-2'` Actions
-------
### addMessageToQueue
Add a message to a queue/tube
```
<?php
$I->addMessageToQueue('this is a messages', 'default');
?>
```
* `param string` $message Message Body
* `param string` $queue Queue Name
### clearQueue
Clear all messages of the queue/tube
```
<?php
$I->clearQueue('default');
?>
```
* `param string` $queue Queue Name
### dontSeeEmptyQueue
Check if a queue/tube is NOT empty of all messages
```
<?php
$I->dontSeeEmptyQueue('default');
?>
```
* `param string` $queue Queue Name
### dontSeeQueueExists
Check if a queue/tube does NOT exist on the queueing server.
```
<?php
$I->dontSeeQueueExists('default');
?>
```
* `param string` $queue Queue Name
### dontSeeQueueHasCurrentCount
Check if a queue/tube does NOT have a given current number of messages
```
<?php
$I->dontSeeQueueHasCurrentCount('default', 10);
?>
```
* `param string` $queue Queue Name
* `param int` $expected Number of messages expected
### dontSeeQueueHasTotalCount
Check if a queue/tube does NOT have a given total number of messages
```
<?php
$I->dontSeeQueueHasTotalCount('default', 10);
?>
```
* `param string` $queue Queue Name
* `param int` $expected Number of messages expected
### grabQueueCurrentCount
Grabber method to get the current number of messages on the queue/tube (pending/ready)
```
<?php
$I->grabQueueCurrentCount('default');
?>
```
* `param string` $queue Queue Name
* `return int` Count
### grabQueueTotalCount
Grabber method to get the total number of messages on the queue/tube
```
<?php
$I->grabQueueTotalCount('default');
?>
```
* `param` $queue Queue Name
* `return int` Count
### grabQueues
Grabber method to get the list of queues/tubes on the server
```
<?php
$queues = $I->grabQueues();
?>
```
* `return array` List of Queues/Tubes
### seeEmptyQueue
Check if a queue/tube is empty of all messages
```
<?php
$I->seeEmptyQueue('default');
?>
```
* `param string` $queue Queue Name
### seeQueueExists
Check if a queue/tube exists on the queueing server.
```
<?php
$I->seeQueueExists('default');
?>
```
* `param string` $queue Queue Name
### seeQueueHasCurrentCount
Check if a queue/tube has a given current number of messages
```
<?php
$I->seeQueueHasCurrentCount('default', 10);
?>
```
* `param string` $queue Queue Name
* `param int` $expected Number of messages expected
### seeQueueHasTotalCount
Check if a queue/tube has a given total number of messages
```
<?php
$I->seeQueueHasTotalCount('default', 10);
?>
```
* `param string` $queue Queue Name
* `param int` $expected Number of messages expected
codeception Mezzio Mezzio
======
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-mezzio
```
Alternatively, you can enable `Mezzio` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module allows you to run tests inside Mezzio.
Uses `config/container.php` file by default.
Status
------
* Maintainer: **Naktibalda**
* Stability: **alpha**
Config
------
* `container` - (default: `config/container.php`) relative path to file which returns Container
* `recreateApplicationBetweenTests` - (default: false) whether to recreate the whole application before each test
* `recreateApplicationBetweenRequests` - (default: false) whether to recreate the whole application before each request
Public properties
-----------------
* application - instance of `\Mezzio\Application`
* container - instance of `\Interop\Container\ContainerInterface`
* client - BrowserKit client
Actions
-------
### \_findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$els = $this->getModule('Mezzio')->_findElements('.items');
$els = $this->getModule('Mezzio')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('Mezzio')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return array` of interactive elements
### \_getResponseContent
*hidden API method, expected to be used from Helper classes*
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
```
<?php
// in Helper class
public function seeResponseContains($text)
{
$this->assertStringContainsString($text, $this->getModule('Mezzio')->_getResponseContent(), "response contains");
}
```
* `return string` @throws ModuleException
### \_loadPage
*hidden API method, expected to be used from Helper classes*
Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step.
```
<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
$this->getModule('Mezzio')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
```
* `param string` $method
* `param string` $uri
* `param string` $content
### \_request
*hidden API method, expected to be used from Helper classes*
Send custom request to a backend using method, uri, parameters, etc. Use it in Helpers to create special request actions, like accessing API Returns a string with response body.
```
<?php
// in Helper class
public function createUserByApi($name) {
$userData = $this->getModule('Mezzio')->_request('POST', '/api/v1/users', ['name' => $name]);
$user = json_decode($userData);
return $user->id;
}
```
Does not load the response into the module so you can’t interact with response page (click, fill forms). To load arbitrary page for interaction, use `_loadPage` method.
* `param string` $method
* `param string` $uri
* `param string` $content
* `return string` @throws ExternalUrlException @see `_loadPage`
### \_savePageSource
*hidden API method, expected to be used from Helper classes*
Saves page source of to a file
```
$this->getModule('Mezzio')->_savePageSource(codecept_output_dir().'page.html');
```
* `param` $filename
### amHttpAuthenticated
Authenticates user for HTTP\_AUTH
* `param string` $username
* `param string` $password
### amOnPage
Opens the page for the given relative URI.
```
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
```
* `param string` $page
### attachFile
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
```
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
```
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### click
Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
```
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### deleteHeader
Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
```
* `param string` $name the name of the header to delete.
### dontSee
Checks that the current page doesn’t contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region.
```
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will ignore strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
```
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn’t a cookie with the given name. You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn’t equal the given string. Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
```
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn’t match the given regular expression.
```
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page. You can also specify expected attributes of this element.
```
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeInCurrentUrl
Checks that the current URI doesn’t contain the given string.
```
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### dontSeeInField
Checks that an input field or textarea doesn’t contain the given value. For fuzzy locators, the field is matched by label text, CSS and XPath.
```
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
```
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn’t been assigned any one of many values, an array can be passed as the value:
```
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn’t contain a link with the given string. If the second parameter is given, only links with a matching “href” attribute will be checked.
```
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param string` $text
* `param string` $url optional
### dontSeeOptionIsSelected
Checks that the given option is not selected.
```
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### dontSeeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->dontSeeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### fillField
Fills a text field or textarea with the given string.
```
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], '[email protected]');
?>
```
* `param` $field
* `param` $value
### followRedirect
Follow pending redirect if there is one.
```
<?php
$I->followRedirect();
```
### grabAttributeFrom
Grabs the value of the given attribute value from the given element. Fails if element is not found.
```
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabCookie
Grabs a cookie value. You can set additional cookie params like `domain`, `path` in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try `$I->wait(0.1)`.
* `param` $cookie
* `param array` $params
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
```
<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param string` $uri optional
### grabMultiple
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
```
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return string[]`
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return string` Current page source code.
### grabTextFrom
Finds and returns the text contents of the given element. If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
```
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
* `param` $field
* `return array|mixed|null|string`
### haveHttpHeader
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
```
To use special chars in Header Key use HTML Character Entities: Example: Header with underscore - ‘Client\_Id’ should be represented as - ‘Client\_Id’ or ‘Client\_Id’
```
<?php
$I->haveHttpHeader('Client_Id', 'Codeception');
```
* `param string` $name the name of the request header
* `param string` $value the value to set it to for subsequent requests
### haveServerParameter
Sets SERVER parameter valid for all next requests.
```
$I->haveServerParameter('name', 'value');
```
* `param string` $name
* `param string` $value
### makeHtmlSnapshot
Use this method within an [interactive pause](../02-gettingstarted#Interactive-Pause) to save the HTML source code of the current page.
```
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
```
* `param null` $name
### moveBack
Moves back in history.
* `param int` $numberOfSteps (default value 1)
### resetCookie
Unsets cookie with the given name. You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.
```
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->see('strong')` will return true for strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
```
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set. You can set additional cookie params like `domain`, `path` as array passed in last argument.
```
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string. Unlike `seeInCurrentUrl`, this only matches the full URL.
```
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
```
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### seeElement
Checks that the given element exists on the page and is visible. You can also specify expected attributes of this element.
```
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
### seeInCurrentUrl
Checks that current URI contains the given string.
```
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### seeInField
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value. Fields are matched by label text, the “name” attribute, CSS, or XPath.
```
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
```
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
```
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
```
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there’s a link with the specified text. Give a full URL as the second parameter to match links with that exact URL.
```
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param string` $text
* `param string` $url optional
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
```
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected int or int[]
### seeOptionIsSelected
Checks that the given option is selected.
```
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### seePageNotFound
Asserts that current page has 404 response status code.
### seeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->seeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### seeResponseCodeIsBetween
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
* `param int` $from
* `param int` $to
### seeResponseCodeIsClientError
Checks that the response code is 4xx
### seeResponseCodeIsRedirection
Checks that the response code 3xx
### seeResponseCodeIsServerError
Checks that the response code is 5xx
### seeResponseCodeIsSuccessful
Checks that the response code 2xx
### selectOption
Selects an option in a select tag or in radio button group.
```
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
```
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
```
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### sendAjaxGetRequest
Sends an ajax GET request with the passed parameters. See `sendAjaxPostRequest()`
* `param` $uri
* `param` $params
### sendAjaxPostRequest
Sends an ajax POST request with the passed parameters. The appropriate HTTP header is added automatically: `X-Requested-With: XMLHttpRequest` Example:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['task' => 'lorem ipsum']);
```
Some frameworks (e.g. Symfony) create field names in the form of an “array”: `<input type="text" name="form[task]">` In this case you need to pass the fields like this:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['form' => [
'task' => 'lorem ipsum',
'category' => 'miscellaneous',
]]);
```
* `param string` $uri
* `param array` $params
### sendAjaxRequest
Sends an ajax request, using the passed HTTP method. See `sendAjaxPostRequest()` Example:
```
<?php
$I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
```
* `param` $method
* `param` $uri
* `param array` $params
### setCookie
Sets a cookie with the given name and value. You can set additional cookie params like `domain`, `path`, `expires`, `secure` in array passed as last argument.
```
<?php
$I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
?>
```
* `param` $name
* `param` $val
* `param array` $params
### setMaxRedirects
Sets the maximum number of redirects that the Client can follow.
```
<?php
$I->setMaxRedirects(2);
```
* `param int` $maxRedirects
### setServerParameters
Sets SERVER parameters valid for all next requests. this will remove old ones.
```
$I->setServerParameters([]);
```
### startFollowingRedirects
Enables automatic redirects to be followed by the client.
```
<?php
$I->startFollowingRedirects();
```
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client.
```
<?php
$I->stopFollowingRedirects();
```
### submitForm
Submits the given form on the page, with the given form values. Pass the form field’s values as an array in the second parameter.
Although this function can be used as a short-hand version of `fillField()`, `selectOption()`, `click()` etc. it has some important differences:
* Only field *names* may be used, not CSS/XPath selectors nor field labels
* If a field is sent to this function that does *not* exist on the page, it will silently be added to the HTTP request. This is helpful for testing some types of forms, but be aware that you will *not* get an exception like you would if you called `fillField()` or `selectOption()` with a missing field.
Fields that are not provided will be filled by their values from the page, or from any previous calls to `fillField()`, `selectOption()` etc. You don’t need to click the ‘Submit’ button afterwards. This command itself triggers the request to form’s action.
You can optionally specify which button’s value to include in the request with the last parameter (as an alternative to explicitly setting its value in the second parameter), as button values are not otherwise included in the request.
Examples:
```
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample “Sign Up” form:
```
<form id="userForm">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Subscribe to our newsletter?
<input type="checkbox" name="user[newsletter]" value="1" checked="checked" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
],
'submitButton'
);
```
Note that “2” will be the submitted value for the “plan” field, as it is the selected option.
To uncheck the pre-checked checkbox “newsletter”, call `$I->uncheckOption(['name' => 'user[newsletter]']);` *before*, then submit the form as shown here (i.e. without the “newsletter” field in the `$params` array).
You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
]
);
```
This function works well when paired with `seeInFormFields()` for quickly testing CRUD interfaces and form validation logic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);
```
Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean `true`/`false` which will be replaced by the checkbox’s value in the DOM.
```
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false
],
'multiselect' => [
'first option value',
'second option value'
]
]);
```
Mixing string and boolean values for a checkbox’s value is not supported and may produce unexpected results.
Field names ending in `[]` must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:
```
<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```
<?php
// This way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
* `param` $selector
* `param` $params
* `param` $button
### switchToIframe
Switch to iframe or frame on the page.
Example:
```
<iframe name="another_frame" src="http://example.com">
```
```
<?php
# switch to iframe
$I->switchToIframe("another_frame");
```
* `param string` $name
### uncheckOption
Unticks a checkbox.
```
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
| programming_docs |
codeception Phalcon Phalcon
=======
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-phalcon
```
Alternatively, you can enable `Phalcon` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module provides integration with [Phalcon framework](http://www.phalcon.io/) (3.x). Please try it and leave your feedback.
Demo Project
------------
<https://github.com/Codeception/phalcon-demo>
Status
------
* Maintainer: **Serghei Iakovlev**
* Stability: **stable**
* Contact: [email protected]
Config
------
The following configurations are required for this module:
* bootstrap: `string`, default `app/config/bootstrap.php` - relative path to app.php config file
* cleanup: `boolean`, default `true` - all database queries will be run in a transaction, which will be rolled back at the end of each test
* savepoints: `boolean`, default `true` - use savepoints to emulate nested transactions
The application bootstrap file must return Application object but not call its handle() method.
API
---
* di - `Phalcon\Di\Injectable` instance
* client - `BrowserKit` client
Parts
-----
By default all available methods are loaded, but you can specify parts to select only needed actions and avoid conflicts.
* `orm` - include only `haveRecord/grabRecord/seeRecord/dontSeeRecord` actions.
* `services` - allows to use `grabServiceFromContainer` and `addServiceToContainer`.
See [WebDriver module](webdriver#Loading-Parts-from-other-Modules) for general information on how to load parts of a framework module.
Usage example:
Sample bootstrap (`app/config/bootstrap.php`):
```
<?php
$config = include __DIR__ . "/config.php";
include __DIR__ . "/loader.php";
$di = new \Phalcon\DI\FactoryDefault();
include __DIR__ . "/services.php";
return new \Phalcon\Mvc\Application($di);
?>
```
```
actor: AcceptanceTester
modules:
enabled:
- Phalcon:
part: services
bootstrap: 'app/config/bootstrap.php'
cleanup: true
savepoints: true
- WebDriver:
url: http://your-url.com
browser: phantomjs
```
Actions
-------
### \_findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$els = $this->getModule('Phalcon')->_findElements('.items');
$els = $this->getModule('Phalcon')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('Phalcon')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return array` of interactive elements
### \_getResponseContent
*hidden API method, expected to be used from Helper classes*
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
```
<?php
// in Helper class
public function seeResponseContains($text)
{
$this->assertStringContainsString($text, $this->getModule('Phalcon')->_getResponseContent(), "response contains");
}
```
* `return string` @throws ModuleException
### \_loadPage
*hidden API method, expected to be used from Helper classes*
Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step.
```
<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
$this->getModule('Phalcon')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
```
* `param string` $method
* `param string` $uri
* `param string` $content
### \_request
*hidden API method, expected to be used from Helper classes*
Send custom request to a backend using method, uri, parameters, etc. Use it in Helpers to create special request actions, like accessing API Returns a string with response body.
```
<?php
// in Helper class
public function createUserByApi($name) {
$userData = $this->getModule('Phalcon')->_request('POST', '/api/v1/users', ['name' => $name]);
$user = json_decode($userData);
return $user->id;
}
```
Does not load the response into the module so you can’t interact with response page (click, fill forms). To load arbitrary page for interaction, use `_loadPage` method.
* `param string` $method
* `param string` $uri
* `param string` $content
* `return string` @throws ExternalUrlException @see `_loadPage`
### \_savePageSource
*hidden API method, expected to be used from Helper classes*
Saves page source of to a file
```
$this->getModule('Phalcon')->_savePageSource(codecept_output_dir().'page.html');
```
* `param` $filename
### addServiceToContainer
Registers a service in the services container and resolve it. This record will be erased after the test. Recommended to use for unit testing.
```
<?php
$filter = $I->addServiceToContainer('filter', ['className' => '\Phalcon\Filter']);
$filter = $I->addServiceToContainer('answer', function () {
return rand(0, 1) ? 'Yes' : 'No';
}, true);
?>
```
* `param string` $name
* `param mixed` $definition
* `param boolean` $shared
* `return mixed|null`
* `[Part]` services
### amHttpAuthenticated
Authenticates user for HTTP\_AUTH
* `param string` $username
* `param string` $password
### amOnPage
Opens the page for the given relative URI.
```
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
```
* `param string` $page
### amOnRoute
Opens web page using route name and parameters.
```
<?php
$I->amOnRoute('posts.create');
?>
```
* `param string` $routeName
* `param array` $params
### attachFile
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
```
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
```
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### click
Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
```
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### deleteHeader
Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
```
* `param string` $name the name of the header to delete.
### dontSee
Checks that the current page doesn’t contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region.
```
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will ignore strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
```
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn’t a cookie with the given name. You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn’t equal the given string. Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
```
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn’t match the given regular expression.
```
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page. You can also specify expected attributes of this element.
```
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeInCurrentUrl
Checks that the current URI doesn’t contain the given string.
```
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### dontSeeInField
Checks that an input field or textarea doesn’t contain the given value. For fuzzy locators, the field is matched by label text, CSS and XPath.
```
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
```
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn’t been assigned any one of many values, an array can be passed as the value:
```
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn’t contain a link with the given string. If the second parameter is given, only links with a matching “href” attribute will be checked.
```
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param string` $text
* `param string` $url optional
### dontSeeOptionIsSelected
Checks that the given option is not selected.
```
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### dontSeeRecord
Checks that record does not exist in database.
```
<?php
$I->dontSeeRecord('App\Models\Categories', ['name' => 'Testing']);
?>
```
* `param string` $model Model name
* `param array` $attributes Model attributes
* `[Part]` orm
### dontSeeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->dontSeeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### fillField
Fills a text field or textarea with the given string.
```
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], '[email protected]');
?>
```
* `param` $field
* `param` $value
### followRedirect
Follow pending redirect if there is one.
```
<?php
$I->followRedirect();
```
### getApplication
Provides access the Phalcon application object.
@see \Codeception\Lib\Connector\Phalcon::getApplication
* `return \Phalcon\Application|\Phalcon\Mvc\Micro`
### grabAttributeFrom
Grabs the value of the given attribute value from the given element. Fails if element is not found.
```
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabCookie
Grabs a cookie value. You can set additional cookie params like `domain`, `path` in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try `$I->wait(0.1)`.
* `param` $cookie
* `param array` $params
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
```
<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param string` $uri optional
### grabMultiple
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
```
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return string[]`
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return string` Current page source code.
### grabRecord
Retrieves record from database
```
<?php
$category = $I->grabRecord('App\Models\Categories', ['name' => 'Testing']);
?>
```
* `param string` $model Model name
* `param array` $attributes Model attributes
* `[Part]` orm
### grabServiceFromContainer
Resolves the service based on its configuration from Phalcon’s DI container Recommended to use for unit testing.
* `param string` $service Service name
* `param array|null` $parameters Parameters [Optional]. Set it to null if you want service container to use parameters defined in the config of the container
* `[Part]` services
### grabTextFrom
Finds and returns the text contents of the given element. If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
```
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
* `param` $field
* `return array|mixed|null|string`
### haveHttpHeader
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
```
To use special chars in Header Key use HTML Character Entities: Example: Header with underscore - ‘Client\_Id’ should be represented as - ‘Client\_Id’ or ‘Client\_Id’
```
<?php
$I->haveHttpHeader('Client_Id', 'Codeception');
```
* `param string` $name the name of the request header
* `param string` $value the value to set it to for subsequent requests
### haveInSession
Sets value to session. Use for authorization.
* `param string` $key
* `param mixed` $val
### haveRecord
Inserts record into the database.
```
<?php
$user_id = $I->haveRecord('App\Models\Users', ['name' => 'Phalcon']);
$I->haveRecord('App\Models\Categories', ['name' => 'Testing']');
?>
```
* `param string` $model Model name
* `param array` $attributes Model attributes
* `[Part]` orm
### haveServerParameter
Sets SERVER parameter valid for all next requests.
```
$I->haveServerParameter('name', 'value');
```
* `param string` $name
* `param string` $value
### makeHtmlSnapshot
Use this method within an [interactive pause](../02-gettingstarted#Interactive-Pause) to save the HTML source code of the current page.
```
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
```
* `param null` $name
### moveBack
Moves back in history.
* `param int` $numberOfSteps (default value 1)
### resetCookie
Unsets cookie with the given name. You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.
```
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->see('strong')` will return true for strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
```
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set. You can set additional cookie params like `domain`, `path` as array passed in last argument.
```
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentRouteIs
Checks that current url matches route
```
<?php
$I->seeCurrentRouteIs('posts.index');
?>
```
* `param string` $routeName
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string. Unlike `seeInCurrentUrl`, this only matches the full URL.
```
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
```
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### seeElement
Checks that the given element exists on the page and is visible. You can also specify expected attributes of this element.
```
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
### seeInCurrentUrl
Checks that current URI contains the given string.
```
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### seeInField
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value. Fields are matched by label text, the “name” attribute, CSS, or XPath.
```
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
```
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
```
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInSession
Checks that session contains value. If value is `null` checks that session has key.
```
<?php
$I->seeInSession('key');
$I->seeInSession('key', 'value');
?>
```
* `param string` $key
* `param mixed` $value
### seeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
```
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there’s a link with the specified text. Give a full URL as the second parameter to match links with that exact URL.
```
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param string` $text
* `param string` $url optional
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
```
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected int or int[]
### seeNumberOfRecords
Checks that number of records exists in database.
```
<?php
$I->seeNumberOfRecords('App\Models\Categories', 3, ['name' => 'Testing']);
?>
```
* `param string` $model Model name
* `param int` $number int number of records
* `param array` $attributes Model attributes
* `[Part]` orm
### seeOptionIsSelected
Checks that the given option is selected.
```
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### seePageNotFound
Asserts that current page has 404 response status code.
### seeRecord
Checks that record exists in database.
```
<?php
$I->seeRecord('App\Models\Categories', ['name' => 'Testing']);
?>
```
* `param string` $model Model name
* `param array` $attributes Model attributes
* `[Part]` orm
### seeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->seeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### seeResponseCodeIsBetween
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
* `param int` $from
* `param int` $to
### seeResponseCodeIsClientError
Checks that the response code is 4xx
### seeResponseCodeIsRedirection
Checks that the response code 3xx
### seeResponseCodeIsServerError
Checks that the response code is 5xx
### seeResponseCodeIsSuccessful
Checks that the response code 2xx
### seeSessionHasValues
Assert that the session has a given list of values.
```
<?php
$I->seeSessionHasValues(['key1', 'key2']);
$I->seeSessionHasValues(['key1' => 'value1', 'key2' => 'value2']);
?>
```
* `param` array $bindings
* `return void`
### selectOption
Selects an option in a select tag or in radio button group.
```
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
```
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
```
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### sendAjaxGetRequest
Sends an ajax GET request with the passed parameters. See `sendAjaxPostRequest()`
* `param` $uri
* `param` $params
### sendAjaxPostRequest
Sends an ajax POST request with the passed parameters. The appropriate HTTP header is added automatically: `X-Requested-With: XMLHttpRequest` Example:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['task' => 'lorem ipsum']);
```
Some frameworks (e.g. Symfony) create field names in the form of an “array”: `<input type="text" name="form[task]">` In this case you need to pass the fields like this:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['form' => [
'task' => 'lorem ipsum',
'category' => 'miscellaneous',
]]);
```
* `param string` $uri
* `param array` $params
### sendAjaxRequest
Sends an ajax request, using the passed HTTP method. See `sendAjaxPostRequest()` Example:
```
<?php
$I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
```
* `param` $method
* `param` $uri
* `param array` $params
### setCookie
Sets a cookie with the given name and value. You can set additional cookie params like `domain`, `path`, `expires`, `secure` in array passed as last argument.
```
<?php
$I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
?>
```
* `param` $name
* `param` $val
* `param array` $params
### setMaxRedirects
Sets the maximum number of redirects that the Client can follow.
```
<?php
$I->setMaxRedirects(2);
```
* `param int` $maxRedirects
### setServerParameters
Sets SERVER parameters valid for all next requests. this will remove old ones.
```
$I->setServerParameters([]);
```
### startFollowingRedirects
Enables automatic redirects to be followed by the client.
```
<?php
$I->startFollowingRedirects();
```
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client.
```
<?php
$I->stopFollowingRedirects();
```
### submitForm
Submits the given form on the page, with the given form values. Pass the form field’s values as an array in the second parameter.
Although this function can be used as a short-hand version of `fillField()`, `selectOption()`, `click()` etc. it has some important differences:
* Only field *names* may be used, not CSS/XPath selectors nor field labels
* If a field is sent to this function that does *not* exist on the page, it will silently be added to the HTTP request. This is helpful for testing some types of forms, but be aware that you will *not* get an exception like you would if you called `fillField()` or `selectOption()` with a missing field.
Fields that are not provided will be filled by their values from the page, or from any previous calls to `fillField()`, `selectOption()` etc. You don’t need to click the ‘Submit’ button afterwards. This command itself triggers the request to form’s action.
You can optionally specify which button’s value to include in the request with the last parameter (as an alternative to explicitly setting its value in the second parameter), as button values are not otherwise included in the request.
Examples:
```
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample “Sign Up” form:
```
<form id="userForm">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Subscribe to our newsletter?
<input type="checkbox" name="user[newsletter]" value="1" checked="checked" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
],
'submitButton'
);
```
Note that “2” will be the submitted value for the “plan” field, as it is the selected option.
To uncheck the pre-checked checkbox “newsletter”, call `$I->uncheckOption(['name' => 'user[newsletter]']);` *before*, then submit the form as shown here (i.e. without the “newsletter” field in the `$params` array).
You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
]
);
```
This function works well when paired with `seeInFormFields()` for quickly testing CRUD interfaces and form validation logic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);
```
Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean `true`/`false` which will be replaced by the checkbox’s value in the DOM.
```
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false
],
'multiselect' => [
'first option value',
'second option value'
]
]);
```
Mixing string and boolean values for a checkbox’s value is not supported and may produce unexpected results.
Field names ending in `[]` must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:
```
<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```
<?php
// This way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
* `param` $selector
* `param` $params
* `param` $button
### switchToIframe
Switch to iframe or frame on the page.
Example:
```
<iframe name="another_frame" src="http://example.com">
```
```
<?php
# switch to iframe
$I->switchToIframe("another_frame");
```
* `param string` $name
### uncheckOption
Unticks a checkbox.
```
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
| programming_docs |
codeception Lumen Lumen
=====
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-lumen
```
Alternatively, you can enable `Lumen` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module allows you to run functional tests for Lumen. Please try it and leave your feedback.
Demo project
------------
<https://github.com/codeception/lumen-module-tests>
Config
------
* cleanup: `boolean`, default `true` - all database queries will be run in a transaction, which will be rolled back at the end of each test.
* bootstrap: `string`, default `bootstrap/app.php` - relative path to app.php config file.
* root: `string`, default `` - root path of the application.
* packages: `string`, default `workbench` - root path of application packages (if any).
* url: `string`, default `http://localhost` - the application URL
API
---
* app - `\Laravel\Lumen\Application`
* config - `array`
Parts
-----
* `ORM`: Only include the database methods of this module:
+ dontSeeRecord
+ grabRecord
+ have
+ haveMultiple
+ haveRecord
+ make
+ makeMultiple
+ seeRecord
See [WebDriver module](webdriver#Loading-Parts-from-other-Modules) for general information on how to load parts of a framework module.
Actions
-------
### \_findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$els = $this->getModule('Lumen')->_findElements('.items');
$els = $this->getModule('Lumen')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('Lumen')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return array` of interactive elements
### \_getResponseContent
*hidden API method, expected to be used from Helper classes*
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
```
<?php
// in Helper class
public function seeResponseContains($text)
{
$this->assertStringContainsString($text, $this->getModule('Lumen')->_getResponseContent(), "response contains");
}
```
* `return string` @throws ModuleException
### \_loadPage
*hidden API method, expected to be used from Helper classes*
Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step.
```
<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
$this->getModule('Lumen')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
```
* `param string` $method
* `param string` $uri
* `param string` $content
### \_request
*hidden API method, expected to be used from Helper classes*
Send custom request to a backend using method, uri, parameters, etc. Use it in Helpers to create special request actions, like accessing API Returns a string with response body.
```
<?php
// in Helper class
public function createUserByApi($name) {
$userData = $this->getModule('Lumen')->_request('POST', '/api/v1/users', ['name' => $name]);
$user = json_decode($userData);
return $user->id;
}
```
Does not load the response into the module so you can’t interact with response page (click, fill forms). To load arbitrary page for interaction, use `_loadPage` method.
* `param string` $method
* `param string` $uri
* `param string` $content
* `return string` @throws ExternalUrlException @see `_loadPage`
### \_savePageSource
*hidden API method, expected to be used from Helper classes*
Saves page source of to a file
```
$this->getModule('Lumen')->_savePageSource(codecept_output_dir().'page.html');
```
* `param` $filename
### amHttpAuthenticated
Authenticates user for HTTP\_AUTH
* `param string` $username
* `param string` $password
### amLoggedAs
Set the authenticated user for the next request. This will not persist between multiple requests.
* `param Authenticatable` $user
* `param string|null` $guardName The guard name
### amOnPage
Opens the page for the given relative URI.
```
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
```
* `param string` $page
### amOnRoute
Opens web page using route name and parameters.
```
<?php
$I->amOnRoute('homepage');
```
* `param string` $routeName
* `param array` $params
### attachFile
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
```
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
```
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### clearApplicationHandlers
Clear the registered application handlers.
```
<?php
$I->clearApplicationHandlers();
```
### click
Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
```
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### deleteHeader
Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
```
* `param string` $name the name of the header to delete.
### dontSee
Checks that the current page doesn’t contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region.
```
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will ignore strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### dontSeeAuthentication
Check that user is not authenticated.
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
```
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn’t a cookie with the given name. You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn’t equal the given string. Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
```
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn’t match the given regular expression.
```
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page. You can also specify expected attributes of this element.
```
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeInCurrentUrl
Checks that the current URI doesn’t contain the given string.
```
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### dontSeeInField
Checks that an input field or textarea doesn’t contain the given value. For fuzzy locators, the field is matched by label text, CSS and XPath.
```
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
```
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn’t been assigned any one of many values, an array can be passed as the value:
```
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn’t contain a link with the given string. If the second parameter is given, only links with a matching “href” attribute will be checked.
```
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param string` $text
* `param string` $url optional
### dontSeeOptionIsSelected
Checks that the given option is not selected.
```
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### dontSeeRecord
Checks that record does not exist in database. You can pass the name of a database table or the class name of an Eloquent model as the first argument.
```
<?php
$I->dontSeeRecord('users', ['name' => 'davert']);
$I->dontSeeRecord('App\Models\User', ['name' => 'davert']);
```
* `param string` $table
* `param array` $attributes
* `[Part]` orm
### dontSeeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->dontSeeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### fillField
Fills a text field or textarea with the given string.
```
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], '[email protected]');
?>
```
* `param` $field
* `param` $value
### followRedirect
Follow pending redirect if there is one.
```
<?php
$I->followRedirect();
```
### getApplication
Provides access the Lumen application object.
### grabAttributeFrom
Grabs the value of the given attribute value from the given element. Fails if element is not found.
```
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabCookie
Grabs a cookie value. You can set additional cookie params like `domain`, `path` in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try `$I->wait(0.1)`.
* `param` $cookie
* `param array` $params
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
```
<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param string` $uri optional
### grabMultiple
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
```
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return string[]`
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return string` Current page source code.
### grabRecord
Retrieves record from database If you pass the name of a database table as the first argument, this method returns an array. You can also pass the class name of an Eloquent model, in that case this method returns an Eloquent model.
```
<?php
$record = $I->grabRecord('users', ['name' => 'davert']); // returns array
$record = $I->grabRecord('App\Models\User', ['name' => 'davert']); // returns Eloquent model
```
* `param string` $table
* `param array` $attributes
* `return array|EloquentModel`
* `[Part]` orm
### grabService
Return an instance of a class from the IoC Container.
Example
```
<?php
// In Lumen
App::bind('foo', function($app)
{
return new FooBar;
});
// Then in test
$service = $I->grabService('foo');
// Will return an instance of FooBar, also works for singletons.
```
* `param string` $class
### grabTextFrom
Finds and returns the text contents of the given element. If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
```
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
* `param` $field
* `return array|mixed|null|string`
### have
Use Lumen’s model factory to create a model.
```
<?php
$I->have('App\Models\User');
$I->have('App\Models\User', ['name' => 'John Doe']);
$I->have('App\Models\User', [], 'admin');
```
@see https://lumen.laravel.com/docs/master/testing#model-factories
* `param string` $model
* `param array` $attributes
* `param string` $name
* `[Part]` orm
### haveApplicationHandler
Register a handler than can be used to modify the Laravel application object after it is initialized. The Laravel application object will be passed as an argument to the handler.
```
<?php
$I->haveApplicationHandler(function($app) {
$app->make('config')->set(['test_value' => '10']);
});
```
* `param` $handler
### haveBinding
Add a binding to the Laravel service container. (https://laravel.com/docs/master/container)
```
<?php
$I->haveBinding('App\MyInterface', 'App\MyImplementation');
```
* `param` $abstract
* `param` $concrete
### haveContextualBinding
Add a contextual binding to the Laravel service container. (https://laravel.com/docs/master/container)
```
<?php
$I->haveContextualBinding('App\MyClass', '$variable', 'value');
// This is similar to the following in your Laravel application
$app->when('App\MyClass')
->needs('$variable')
->give('value');
```
* `param` $concrete
* `param` $abstract
* `param` $implementation
### haveHttpHeader
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
```
To use special chars in Header Key use HTML Character Entities: Example: Header with underscore - ‘Client\_Id’ should be represented as - ‘Client\_Id’ or ‘Client\_Id’
```
<?php
$I->haveHttpHeader('Client_Id', 'Codeception');
```
* `param string` $name the name of the request header
* `param string` $value the value to set it to for subsequent requests
### haveInstance
Add an instance binding to the Laravel service container. (https://laravel.com/docs/master/container)
```
<?php
$I->haveInstance('App\MyClass', new App\MyClass());
```
* `param` $abstract
* `param` $instance
### haveMultiple
Use Laravel model factory to create multiple models.
```
<?php
$I->haveMultiple('App\Models\User', 10);
$I->haveMultiple('App\Models\User', 10, ['name' => 'John Doe']);
$I->haveMultiple('App\Models\User', 10, [], 'admin');
```
@see https://lumen.laravel.com/docs/master/testing#model-factories
* `param string` $model
* `param int` $times
* `param array` $attributes
* `param string` $name
* `[Part]` orm
### haveRecord
Inserts record into the database. If you pass the name of a database table as the first argument, this method returns an integer ID. You can also pass the class name of an Eloquent model, in that case this method returns an Eloquent model.
```
<?php
$userId = $I->haveRecord('users', ['name' => 'Davert']); // returns integer
$user = $I->haveRecord('App\Models\User', ['name' => 'Davert']); // returns Eloquent model
```
* `param string` $table
* `param array` $attributes
* `return integer|EloquentModel`
* `[Part]` orm
### haveServerParameter
Sets SERVER parameter valid for all next requests.
```
$I->haveServerParameter('name', 'value');
```
* `param string` $name
* `param string` $value
### haveSingleton
Add a singleton binding to the Laravel service container. (https://laravel.com/docs/master/container)
```
<?php
$I->haveSingleton('My\Interface', 'My\Singleton');
```
* `param` $abstract
* `param` $concrete
### make
Use Lumen’s model factory to make a model instance.
```
<?php
$I->make('App\Models\User');
$I->make('App\Models\User', ['name' => 'John Doe']);
$I->make('App\Models\User', [], 'admin');
```
@see https://lumen.laravel.com/docs/master/testing#model-factories
* `param string` $model
* `param array` $attributes
* `param string` $name
* `[Part]` orm
### makeHtmlSnapshot
Use this method within an [interactive pause](../02-gettingstarted#Interactive-Pause) to save the HTML source code of the current page.
```
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
```
* `param null` $name
### makeMultiple
Use Laravel model factory to make multiple model instances.
```
<?php
$I->makeMultiple('App\Models\User', 10);
$I->makeMultiple('App\Models\User', 10, ['name' => 'John Doe']);
$I->makeMultiple('App\Models\User', 10, [], 'admin');
```
@see https://lumen.laravel.com/docs/master/testing#model-factories
* `param string` $model
* `param int` $times
* `param array` $attributes
* `param string` $name
* `[Part]` orm
### moveBack
Moves back in history.
* `param int` $numberOfSteps (default value 1)
### resetCookie
Unsets cookie with the given name. You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.
```
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->see('strong')` will return true for strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### seeAuthentication
Checks that user is authenticated.
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
```
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set. You can set additional cookie params like `domain`, `path` as array passed in last argument.
```
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string. Unlike `seeInCurrentUrl`, this only matches the full URL.
```
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
```
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### seeElement
Checks that the given element exists on the page and is visible. You can also specify expected attributes of this element.
```
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
### seeInCurrentUrl
Checks that current URI contains the given string.
```
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### seeInField
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value. Fields are matched by label text, the “name” attribute, CSS, or XPath.
```
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
```
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
```
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
```
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there’s a link with the specified text. Give a full URL as the second parameter to match links with that exact URL.
```
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param string` $text
* `param string` $url optional
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
```
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected int or int[]
### seeOptionIsSelected
Checks that the given option is selected.
```
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### seePageNotFound
Asserts that current page has 404 response status code.
### seeRecord
Checks that record exists in database. You can pass the name of a database table or the class name of an Eloquent model as the first argument.
```
<?php
$I->seeRecord('users', ['name' => 'Davert']);
$I->seeRecord('App\Models\User', ['name' => 'Davert']);
?>
```
* `param string` $table
* `param array` $attributes
* `[Part]` orm
### seeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->seeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### seeResponseCodeIsBetween
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
* `param int` $from
* `param int` $to
### seeResponseCodeIsClientError
Checks that the response code is 4xx
### seeResponseCodeIsRedirection
Checks that the response code 3xx
### seeResponseCodeIsServerError
Checks that the response code is 5xx
### seeResponseCodeIsSuccessful
Checks that the response code 2xx
### selectOption
Selects an option in a select tag or in radio button group.
```
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
```
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
```
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### sendAjaxGetRequest
Sends an ajax GET request with the passed parameters. See `sendAjaxPostRequest()`
* `param` $uri
* `param` $params
### sendAjaxPostRequest
Sends an ajax POST request with the passed parameters. The appropriate HTTP header is added automatically: `X-Requested-With: XMLHttpRequest` Example:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['task' => 'lorem ipsum']);
```
Some frameworks (e.g. Symfony) create field names in the form of an “array”: `<input type="text" name="form[task]">` In this case you need to pass the fields like this:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['form' => [
'task' => 'lorem ipsum',
'category' => 'miscellaneous',
]]);
```
* `param string` $uri
* `param array` $params
### sendAjaxRequest
Sends an ajax request, using the passed HTTP method. See `sendAjaxPostRequest()` Example:
```
<?php
$I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
```
* `param` $method
* `param` $uri
* `param array` $params
### setApplication
**not documented**
### setCookie
Sets a cookie with the given name and value. You can set additional cookie params like `domain`, `path`, `expires`, `secure` in array passed as last argument.
```
<?php
$I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
?>
```
* `param` $name
* `param` $val
* `param array` $params
### setMaxRedirects
Sets the maximum number of redirects that the Client can follow.
```
<?php
$I->setMaxRedirects(2);
```
* `param int` $maxRedirects
### setServerParameters
Sets SERVER parameters valid for all next requests. this will remove old ones.
```
$I->setServerParameters([]);
```
### startFollowingRedirects
Enables automatic redirects to be followed by the client.
```
<?php
$I->startFollowingRedirects();
```
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client.
```
<?php
$I->stopFollowingRedirects();
```
### submitForm
Submits the given form on the page, with the given form values. Pass the form field’s values as an array in the second parameter.
Although this function can be used as a short-hand version of `fillField()`, `selectOption()`, `click()` etc. it has some important differences:
* Only field *names* may be used, not CSS/XPath selectors nor field labels
* If a field is sent to this function that does *not* exist on the page, it will silently be added to the HTTP request. This is helpful for testing some types of forms, but be aware that you will *not* get an exception like you would if you called `fillField()` or `selectOption()` with a missing field.
Fields that are not provided will be filled by their values from the page, or from any previous calls to `fillField()`, `selectOption()` etc. You don’t need to click the ‘Submit’ button afterwards. This command itself triggers the request to form’s action.
You can optionally specify which button’s value to include in the request with the last parameter (as an alternative to explicitly setting its value in the second parameter), as button values are not otherwise included in the request.
Examples:
```
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample “Sign Up” form:
```
<form id="userForm">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Subscribe to our newsletter?
<input type="checkbox" name="user[newsletter]" value="1" checked="checked" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
],
'submitButton'
);
```
Note that “2” will be the submitted value for the “plan” field, as it is the selected option.
To uncheck the pre-checked checkbox “newsletter”, call `$I->uncheckOption(['name' => 'user[newsletter]']);` *before*, then submit the form as shown here (i.e. without the “newsletter” field in the `$params` array).
You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
]
);
```
This function works well when paired with `seeInFormFields()` for quickly testing CRUD interfaces and form validation logic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);
```
Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean `true`/`false` which will be replaced by the checkbox’s value in the DOM.
```
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false
],
'multiselect' => [
'first option value',
'second option value'
]
]);
```
Mixing string and boolean values for a checkbox’s value is not supported and may produce unexpected results.
Field names ending in `[]` must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:
```
<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```
<?php
// This way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
* `param` $selector
* `param` $params
* `param` $button
### switchToIframe
Switch to iframe or frame on the page.
Example:
```
<iframe name="another_frame" src="http://example.com">
```
```
<?php
# switch to iframe
$I->switchToIframe("another_frame");
```
* `param string` $name
### uncheckOption
Unticks a checkbox.
```
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
| programming_docs |
codeception AMQP AMQP
====
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-amqp
```
Alternatively, you can enable `AMQP` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module interacts with message broker software that implements the Advanced Message Queuing Protocol (AMQP) standard. For example, RabbitMQ (tested).
To use this module with Composer you need *"php-amqplib/php-amqplib": "~2.4"* package. Config
------
* host: localhost - host to connect
* username: guest - username to connect
* password: guest - password to connect
* vhost: ‘/’ - vhost to connect
* cleanup: true - defined queues will be purged before running every test.
* queues: [mail, twitter] - queues to cleanup
* single\_channel - create and use only one channel during test execution
### Example
`modules:
enabled:
- AMQP:
host: 'localhost'
port: '5672'
username: 'guest'
password: 'guest'
vhost: '/'
queues: [queue1, queue2]
single_channel: false` Public Properties
-----------------
* connection - AMQPStreamConnection - current connection
Actions
-------
### bindQueueToExchange
Binds a queue to an exchange
This is an alias of method `queue_bind` of `PhpAmqpLib\Channel\AMQPChannel`.
```
<?php
$I->bindQueueToExchange(
'nameOfMyQueueToBind', // name of the queue
'transactionTracking.transaction', // exchange name to bind to
'your.routing.key' // Optionally, provide a binding key
)
```
* `param string` $queue
* `param string` $exchange
* `param string` $routing\_key
* `param bool` $nowait
* `param array` $arguments
* `param int` $ticket
* `return mixed|null`
### declareExchange
Declares an exchange
This is an alias of method `exchange_declare` of `PhpAmqpLib\Channel\AMQPChannel`.
```
<?php
$I->declareExchange(
'nameOfMyExchange', // exchange name
'topic' // exchange type
)
```
* `param string` $exchange
* `param string` $type
* `param bool` $passive
* `param bool` $durable
* `param bool` $auto\_delete
* `param bool` $internal
* `param bool` $nowait
* `param array` $arguments
* `param int` $ticket
* `return mixed|null`
### declareQueue
Declares queue, creates if needed
This is an alias of method `queue_declare` of `PhpAmqpLib\Channel\AMQPChannel`.
```
<?php
$I->declareQueue(
'nameOfMyQueue', // exchange name
)
```
* `param string` $queue
* `param bool` $passive
* `param bool` $durable
* `param bool` $exclusive
* `param bool` $auto\_delete
* `param bool` $nowait
* `param array` $arguments
* `param int` $ticket
* `return mixed|null`
### dontSeeQueueIsEmpty
Checks if queue is not empty.
```
<?php
$I->pushToQueue('queue.emails', 'Hello, davert');
$I->dontSeeQueueIsEmpty('queue.emails');
?>
```
* `param string` $queue
### grabMessageFromQueue
Takes last message from queue.
```
<?php
$message = $I->grabMessageFromQueue('queue.emails');
?>
```
* `param string` $queue
* `return \PhpAmqpLib\Message\AMQPMessage`
### purgeAllQueues
Purge all queues defined in config.
```
<?php
$I->purgeAllQueues();
?>
```
### purgeQueue
Purge a specific queue defined in config.
```
<?php
$I->purgeQueue('queue.emails');
?>
```
* `param string` $queueName
### pushToExchange
Sends message to exchange by sending exchange name, message and (optionally) a routing key
```
<?php
$I->pushToExchange('exchange.emails', 'thanks');
$I->pushToExchange('exchange.emails', new AMQPMessage('Thanks!'));
$I->pushToExchange('exchange.emails', new AMQPMessage('Thanks!'), 'severity');
?>
```
* `param string` $exchange
* `param string|\PhpAmqpLib\Message\AMQPMessage` $message
* `param string` $routing\_key
### pushToQueue
Sends message to queue
```
<?php
$I->pushToQueue('queue.jobs', 'create user');
$I->pushToQueue('queue.jobs', new AMQPMessage('create'));
?>
```
* `param string` $queue
* `param string|\PhpAmqpLib\Message\AMQPMessage` $message
### scheduleQueueCleanup
Add a queue to purge list
* `param string` $queue
### seeMessageInQueueContainsText
Checks if message containing text received.
**This method drops message from queue** **This method will wait for message. If none is sent the script will stuck**.
```
<?php
$I->pushToQueue('queue.emails', 'Hello, davert');
$I->seeMessageInQueueContainsText('queue.emails','davert');
?>
```
* `param string` $queue
* `param string` $text
### seeNumberOfMessagesInQueue
Checks that queue have expected number of message
```
<?php
$I->pushToQueue('queue.emails', 'Hello, davert');
$I->seeNumberOfMessagesInQueue('queue.emails',1);
?>
```
* `param string` $queue
* `param int` $expected
### seeQueueIsEmpty
Checks that queue is empty
```
<?php
$I->pushToQueue('queue.emails', 'Hello, davert');
$I->purgeQueue('queue.emails');
$I->seeQueueIsEmpty('queue.emails');
?>
```
* `param string` $queue
* `param int` $expected
codeception PhpBrowser PhpBrowser
==========
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-phpbrowser
```
Alternatively, you can enable `PhpBrowser` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Uses [Guzzle](http://guzzlephp.org/) to interact with your application over CURL. Module works over CURL and requires **PHP CURL extension** to be enabled.
Use to perform web acceptance tests with non-javascript browser.
If test fails stores last shown page in ‘output’ dir.
Status
------
* Maintainer: **davert**
* Stability: **stable**
* Contact: [email protected]
Configuration
-------------
* url *required* - start url of your app
* headers - default headers are set before each test.
* handler (default: curl) - Guzzle handler to use. By default curl is used, also possible to pass `stream`, or any valid class name as [Handler](http://docs.guzzlephp.org/en/latest/handlers-and-middleware.html#handlers).
* middleware - Guzzle middlewares to add. An array of valid callables is required.
* curl - curl options
* cookies - …
* auth - …
* verify - …
* .. those and other [Guzzle Request options](http://docs.guzzlephp.org/en/latest/request-options.html)
### Example (`acceptance.suite.yml`)
`modules:
enabled:
- PhpBrowser:
url: 'http://localhost'
auth: ['admin', '123345']
curl:
CURLOPT_RETURNTRANSFER: true
cookies:
cookie-1:
Name: userName
Value: john.doe
cookie-2:
Name: authToken
Value: 1abcd2345
Domain: subdomain.domain.com
Path: /admin/
Expires: 1292177455
Secure: true
HttpOnly: false` All SSL certification checks are disabled by default. Use Guzzle request options to configure certifications and others.
Public API
----------
Those properties and methods are expected to be used in Helper classes:
Properties:
* `guzzle` - contains [Guzzle](http://guzzlephp.org/) client instance: `\GuzzleHttp\Client`
* `client` - Symfony BrowserKit instance.
Actions
-------
### \_findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$els = $this->getModule('PhpBrowser')->_findElements('.items');
$els = $this->getModule('PhpBrowser')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('PhpBrowser')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return array` of interactive elements
### \_getResponseContent
*hidden API method, expected to be used from Helper classes*
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
```
<?php
// in Helper class
public function seeResponseContains($text)
{
$this->assertStringContainsString($text, $this->getModule('PhpBrowser')->_getResponseContent(), "response contains");
}
```
* `return string` @throws ModuleException
### \_loadPage
*hidden API method, expected to be used from Helper classes*
Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step.
```
<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
$this->getModule('PhpBrowser')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
```
* `param string` $method
* `param string` $uri
* `param string` $content
### \_request
*hidden API method, expected to be used from Helper classes*
Send custom request to a backend using method, uri, parameters, etc. Use it in Helpers to create special request actions, like accessing API Returns a string with response body.
```
<?php
// in Helper class
public function createUserByApi($name) {
$userData = $this->getModule('PhpBrowser')->_request('POST', '/api/v1/users', ['name' => $name]);
$user = json_decode($userData);
return $user->id;
}
```
Does not load the response into the module so you can’t interact with response page (click, fill forms). To load arbitrary page for interaction, use `_loadPage` method.
* `param string` $method
* `param string` $uri
* `param string` $content
* `return string` @throws ExternalUrlException @see `_loadPage`
### \_savePageSource
*hidden API method, expected to be used from Helper classes*
Saves page source of to a file
```
$this->getModule('PhpBrowser')->_savePageSource(codecept_output_dir().'page.html');
```
* `param` $filename
### amHttpAuthenticated
Authenticates user for HTTP\_AUTH
* `param string` $username
* `param string` $password
### amOnPage
Opens the page for the given relative URI.
```
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
```
* `param string` $page
### amOnSubdomain
Changes the subdomain for the ‘url’ configuration parameter. Does not open a page; use `amOnPage` for that.
```
<?php
// If config is: 'http://mysite.com'
// or config is: 'http://www.mysite.com'
// or config is: 'http://company.mysite.com'
$I->amOnSubdomain('user');
$I->amOnPage('/');
// moves to http://user.mysite.com/
?>
```
* `param` $subdomain
### amOnUrl
Open web page at the given absolute URL and sets its hostname as the base host.
```
<?php
$I->amOnUrl('http://codeception.com');
$I->amOnPage('/quickstart'); // moves to http://codeception.com/quickstart
?>
```
### attachFile
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
```
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
```
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### click
Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
```
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### deleteHeader
Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
```
* `param string` $name the name of the header to delete.
### dontSee
Checks that the current page doesn’t contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region.
```
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will ignore strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
```
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn’t a cookie with the given name. You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn’t equal the given string. Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
```
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn’t match the given regular expression.
```
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page. You can also specify expected attributes of this element.
```
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeInCurrentUrl
Checks that the current URI doesn’t contain the given string.
```
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### dontSeeInField
Checks that an input field or textarea doesn’t contain the given value. For fuzzy locators, the field is matched by label text, CSS and XPath.
```
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
```
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn’t been assigned any one of many values, an array can be passed as the value:
```
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn’t contain a link with the given string. If the second parameter is given, only links with a matching “href” attribute will be checked.
```
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param string` $text
* `param string` $url optional
### dontSeeOptionIsSelected
Checks that the given option is not selected.
```
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### dontSeeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->dontSeeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### executeInGuzzle
Low-level API method. If Codeception commands are not enough, use [Guzzle HTTP Client](http://guzzlephp.org/) methods directly
Example:
```
<?php
$I->executeInGuzzle(function (\GuzzleHttp\Client $client) {
$client->get('/get', ['query' => ['foo' => 'bar']]);
});
?>
```
It is not recommended to use this command on a regular basis. If Codeception lacks important Guzzle Client methods, implement them and submit patches.
* `param Closure` $function
### fillField
Fills a text field or textarea with the given string.
```
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], '[email protected]');
?>
```
* `param` $field
* `param` $value
### followRedirect
Follow pending redirect if there is one.
```
<?php
$I->followRedirect();
```
### grabAttributeFrom
Grabs the value of the given attribute value from the given element. Fails if element is not found.
```
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabCookie
Grabs a cookie value. You can set additional cookie params like `domain`, `path` in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try `$I->wait(0.1)`.
* `param` $cookie
* `param array` $params
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
```
<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param string` $uri optional
### grabMultiple
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
```
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return string[]`
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return string` Current page source code.
### grabTextFrom
Finds and returns the text contents of the given element. If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
```
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
* `param` $field
* `return array|mixed|null|string`
### haveHttpHeader
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
```
To use special chars in Header Key use HTML Character Entities: Example: Header with underscore - ‘Client\_Id’ should be represented as - ‘Client\_Id’ or ‘Client\_Id’
```
<?php
$I->haveHttpHeader('Client_Id', 'Codeception');
```
* `param string` $name the name of the request header
* `param string` $value the value to set it to for subsequent requests
### haveServerParameter
Sets SERVER parameter valid for all next requests.
```
$I->haveServerParameter('name', 'value');
```
* `param string` $name
* `param string` $value
### makeHtmlSnapshot
Use this method within an [interactive pause](../02-gettingstarted#Interactive-Pause) to save the HTML source code of the current page.
```
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
```
* `param null` $name
### moveBack
Moves back in history.
* `param int` $numberOfSteps (default value 1)
### resetCookie
Unsets cookie with the given name. You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.
```
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->see('strong')` will return true for strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
```
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set. You can set additional cookie params like `domain`, `path` as array passed in last argument.
```
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string. Unlike `seeInCurrentUrl`, this only matches the full URL.
```
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
```
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### seeElement
Checks that the given element exists on the page and is visible. You can also specify expected attributes of this element.
```
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
### seeInCurrentUrl
Checks that current URI contains the given string.
```
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### seeInField
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value. Fields are matched by label text, the “name” attribute, CSS, or XPath.
```
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
```
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
```
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
```
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there’s a link with the specified text. Give a full URL as the second parameter to match links with that exact URL.
```
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param string` $text
* `param string` $url optional
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
```
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected int or int[]
### seeOptionIsSelected
Checks that the given option is selected.
```
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### seePageNotFound
Asserts that current page has 404 response status code.
### seeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->seeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### seeResponseCodeIsBetween
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
* `param int` $from
* `param int` $to
### seeResponseCodeIsClientError
Checks that the response code is 4xx
### seeResponseCodeIsRedirection
Checks that the response code 3xx
### seeResponseCodeIsServerError
Checks that the response code is 5xx
### seeResponseCodeIsSuccessful
Checks that the response code 2xx
### selectOption
Selects an option in a select tag or in radio button group.
```
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
```
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
```
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### sendAjaxGetRequest
Sends an ajax GET request with the passed parameters. See `sendAjaxPostRequest()`
* `param` $uri
* `param` $params
### sendAjaxPostRequest
Sends an ajax POST request with the passed parameters. The appropriate HTTP header is added automatically: `X-Requested-With: XMLHttpRequest` Example:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['task' => 'lorem ipsum']);
```
Some frameworks (e.g. Symfony) create field names in the form of an “array”: `<input type="text" name="form[task]">` In this case you need to pass the fields like this:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['form' => [
'task' => 'lorem ipsum',
'category' => 'miscellaneous',
]]);
```
* `param string` $uri
* `param array` $params
### sendAjaxRequest
Sends an ajax request, using the passed HTTP method. See `sendAjaxPostRequest()` Example:
```
<?php
$I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
```
* `param` $method
* `param` $uri
* `param array` $params
### setCookie
Sets a cookie with the given name and value. You can set additional cookie params like `domain`, `path`, `expires`, `secure` in array passed as last argument.
```
<?php
$I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
?>
```
* `param` $name
* `param` $val
* `param array` $params
### setHeader
Alias to `haveHttpHeader`
* `param` $name
* `param` $value
### setMaxRedirects
Sets the maximum number of redirects that the Client can follow.
```
<?php
$I->setMaxRedirects(2);
```
* `param int` $maxRedirects
### setServerParameters
Sets SERVER parameters valid for all next requests. this will remove old ones.
```
$I->setServerParameters([]);
```
### startFollowingRedirects
Enables automatic redirects to be followed by the client.
```
<?php
$I->startFollowingRedirects();
```
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client.
```
<?php
$I->stopFollowingRedirects();
```
### submitForm
Submits the given form on the page, with the given form values. Pass the form field’s values as an array in the second parameter.
Although this function can be used as a short-hand version of `fillField()`, `selectOption()`, `click()` etc. it has some important differences:
* Only field *names* may be used, not CSS/XPath selectors nor field labels
* If a field is sent to this function that does *not* exist on the page, it will silently be added to the HTTP request. This is helpful for testing some types of forms, but be aware that you will *not* get an exception like you would if you called `fillField()` or `selectOption()` with a missing field.
Fields that are not provided will be filled by their values from the page, or from any previous calls to `fillField()`, `selectOption()` etc. You don’t need to click the ‘Submit’ button afterwards. This command itself triggers the request to form’s action.
You can optionally specify which button’s value to include in the request with the last parameter (as an alternative to explicitly setting its value in the second parameter), as button values are not otherwise included in the request.
Examples:
```
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample “Sign Up” form:
```
<form id="userForm">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Subscribe to our newsletter?
<input type="checkbox" name="user[newsletter]" value="1" checked="checked" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
],
'submitButton'
);
```
Note that “2” will be the submitted value for the “plan” field, as it is the selected option.
To uncheck the pre-checked checkbox “newsletter”, call `$I->uncheckOption(['name' => 'user[newsletter]']);` *before*, then submit the form as shown here (i.e. without the “newsletter” field in the `$params` array).
You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
]
);
```
This function works well when paired with `seeInFormFields()` for quickly testing CRUD interfaces and form validation logic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);
```
Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean `true`/`false` which will be replaced by the checkbox’s value in the DOM.
```
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false
],
'multiselect' => [
'first option value',
'second option value'
]
]);
```
Mixing string and boolean values for a checkbox’s value is not supported and may produce unexpected results.
Field names ending in `[]` must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:
```
<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```
<?php
// This way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
* `param` $selector
* `param` $params
* `param` $button
### switchToIframe
Switch to iframe or frame on the page.
Example:
```
<iframe name="another_frame" src="http://example.com">
```
```
<?php
# switch to iframe
$I->switchToIframe("another_frame");
```
* `param string` $name
### uncheckOption
Unticks a checkbox.
```
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
| programming_docs |
codeception Apc Apc
===
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-apc
```
Alternatively, you can enable `Apc` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module interacts with the [Alternative PHP Cache (APC)](https://php.net/manual/en/intro.apcu.php) using either *APCu* or *APC* extension.
Performs a cleanup by flushing all values after each test run.
Status
------
* Maintainer: **Serghei Iakovlev**
* Stability: **stable**
* Contact: [email protected]
### Example (`unit.suite.yml`)
```
modules:
- Apc
```
Be sure you don’t use the production server to connect.
Actions
-------
### dontSeeInApc
Checks item in APC(u) doesn’t exist or is the same as expected.
Examples:
```
<?php
// With only one argument, only checks the key does not exist
$I->dontSeeInApc('users_count');
// Checks a 'users_count' exists does not exist or its value is not the one provided
$I->dontSeeInApc('users_count', 200);
?>
```
* `param string|string[]` $key
* `param mixed` $value
### flushApc
Clears the APC(u) cache
### grabValueFromApc
Grabs value from APC(u) by key.
Example:
```
<?php
$users_count = $I->grabValueFromApc('users_count');
?>
```
* `param string|string[]` $key
### haveInApc
Stores an item `$value` with `$key` on the APC(u).
Examples:
```
<?php
// Array
$I->haveInApc('users', ['name' => 'miles', 'email' => '[email protected]']);
// Object
$I->haveInApc('user', UserRepository::findFirst());
// Key as array of 'key => value'
$entries = [];
$entries['key1'] = 'value1';
$entries['key2'] = 'value2';
$entries['key3'] = ['value3a','value3b'];
$entries['key4'] = 4;
$I->haveInApc($entries, null);
?>
```
* `param string|array` $key
* `param mixed` $value
* `param int` $expiration
### seeInApc
Checks item in APC(u) exists and the same as expected.
Examples:
```
<?php
// With only one argument, only checks the key exists
$I->seeInApc('users_count');
// Checks a 'users_count' exists and has the value 200
$I->seeInApc('users_count', 200);
?>
```
* `param string|string[]` $key
* `param mixed` $value
codeception Cli Cli
===
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-cli
```
Alternatively, you can enable `Cli` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Wrapper for basic shell commands and shell output
Responsibility
--------------
* Maintainer: **davert**
* Status: **stable**
* Contact: [email protected]
*Please review the code of non-stable modules and provide patches if you have issues.*
Actions
-------
### dontSeeInShellOutput
Checks that output from latest command doesn’t contain text
* `param` $text
### grabShellOutput
Returns the output from latest command
### runShellCommand
Executes a shell command. Fails if exit code is > 0. You can disable this by passing `false` as second argument
```
<?php
$I->runShellCommand('phpunit');
// do not fail test when command fails
$I->runShellCommand('phpunit', false);
```
* `param` $command
* `param bool` $failNonZero
### seeInShellOutput
Checks that output from last executed command contains text
* `param` $text
### seeResultCodeIs
Checks result code. To verify a result code > 0, you need to pass `false` as second argument to `runShellCommand()`
```
<?php
$I->seeResultCodeIs(0);
```
* `param` $code
### seeResultCodeIsNot
Checks result code
```
<?php
$I->seeResultCodeIsNot(0);
```
* `param` $code
### seeShellOutputMatches
* `param` $regex
codeception Symfony Symfony
=======
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-symfony
```
Alternatively, you can enable `Symfony` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module uses [Symfony’s DomCrawler](https://symfony.com/doc/current/components/dom_crawler.html) and [HttpKernel Component](https://symfony.com/doc/current/components/http_kernel.html) to emulate requests and test response.
* Access Symfony services through the dependency injection container: [`$I->grabService(...)`](#grabService)
* Use Doctrine to test against the database: `$I->seeInRepository(...)` - see [Doctrine Module](doctrine2)
* Assert that emails would have been sent: [`$I->seeEmailIsSent()`](#seeEmailIsSent)
* Tests are wrapped into Doctrine transaction to speed them up.
* Symfony Router can be cached between requests to speed up testing.
Demo Project
------------
<https://github.com/Codeception/symfony-module-tests>
Config
------
### Symfony 5.x or 4.4
* app\_path: ‘src’ - Specify custom path to your app dir, where the kernel interface is located.
* environment: ‘local’ - Environment used for load kernel
* kernel\_class: ‘App\Kernel’ - Kernel class name
* em\_service: ‘doctrine.orm.entity\_manager’ - Use the stated EntityManager to pair with Doctrine Module.
* debug: true - Turn on/off debug mode
* cache\_router: ‘false’ - Enable router caching between tests in order to [increase performance](http://lakion.com/blog/how-did-we-speed-up-sylius-behat-suite-with-blackfire)
* rebootable\_client: ‘true’ - Reboot client’s kernel before each request
##### Example (`functional.suite.yml`) - Symfony 4 Directory Structure
`modules:
enabled:
- Symfony:
app_path: 'src'
environment: 'test'` Public Properties
-----------------
* kernel - HttpKernel instance
* client - current Crawler instance
Parts
-----
* `services`: Includes methods related to the Symfony dependency injection container (DIC):
+ grabService
+ persistService
+ persistPermanentService
+ unpersistService
See [WebDriver module](webdriver#Loading-Parts-from-other-Modules) for general information on how to load parts of a framework module.
Usage example:
```
actor: AcceptanceTester
modules:
enabled:
- Symfony:
part: services
- Doctrine2:
depends: Symfony
- WebDriver:
url: http://example.com
browser: firefox
```
If you’re using Symfony with Eloquent ORM (instead of Doctrine), you can load the [`ORM` part of Laravel module](laravel5#Parts) in addition to Symfony module.
Actions
-------
### \_findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$els = $this->getModule('Symfony')->_findElements('.items');
$els = $this->getModule('Symfony')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('Symfony')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return array` of interactive elements
### \_getResponseContent
*hidden API method, expected to be used from Helper classes*
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
```
<?php
// in Helper class
public function seeResponseContains($text)
{
$this->assertStringContainsString($text, $this->getModule('Symfony')->_getResponseContent(), "response contains");
}
```
* `return string` @throws ModuleException
### \_loadPage
*hidden API method, expected to be used from Helper classes*
Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step.
```
<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
$this->getModule('Symfony')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
```
* `param string` $method
* `param string` $uri
* `param string` $content
### \_request
*hidden API method, expected to be used from Helper classes*
Send custom request to a backend using method, uri, parameters, etc. Use it in Helpers to create special request actions, like accessing API Returns a string with response body.
```
<?php
// in Helper class
public function createUserByApi($name) {
$userData = $this->getModule('Symfony')->_request('POST', '/api/v1/users', ['name' => $name]);
$user = json_decode($userData);
return $user->id;
}
```
Does not load the response into the module so you can’t interact with response page (click, fill forms). To load arbitrary page for interaction, use `_loadPage` method.
* `param string` $method
* `param string` $uri
* `param string` $content
* `return string` @throws ExternalUrlException @see `_loadPage`
### \_savePageSource
*hidden API method, expected to be used from Helper classes*
Saves page source of to a file
```
$this->getModule('Symfony')->_savePageSource(codecept_output_dir().'page.html');
```
* `param` $filename
### amHttpAuthenticated
Authenticates user for HTTP\_AUTH
* `param string` $username
* `param string` $password
### amLoggedInAs
Login with the given user object. The `$user` object must have a persistent identifier. If you have more than one firewall or firewall context, you can specify the desired one as a parameter.
```
<?php
$user = $I->grabEntityFromRepository(User::class, [
'email' => '[email protected]'
]);
$I->amLoggedInAs($user);
```
* `param UserInterface` $user
* `param string` $firewallName
* `param null` $firewallContext
### amOnAction
Opens web page by action name
```
<?php
$I->amOnAction('PostController::index');
$I->amOnAction('HomeController');
$I->amOnAction('ArticleController', ['slug' => 'lorem-ipsum']);
```
* `param string` $action
* `param array` $params
### amOnPage
Opens the page for the given relative URI.
```
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
```
* `param string` $page
### amOnRoute
Opens web page using route name and parameters.
```
<?php
$I->amOnRoute('posts.create');
$I->amOnRoute('posts.show', ['id' => 34]);
```
* `param string` $routeName
* `param array` $params
### assertEmailAddressContains
Verify that an email contains addresses with a [header](https://datatracker.ietf.org/doc/html/rfc4021) `$headerName` and its expected value `$expectedValue`. If the Email object is not specified, the last email sent is used instead.
```
<?php
$I->assertEmailAddressContains('To', '[email protected]');
```
### assertEmailAttachmentCount
Verify that an email has sent the specified number `$count` of attachments. If the Email object is not specified, the last email sent is used instead.
```
<?php
$I->assertEmailAttachmentCount(1);
```
### assertEmailHasHeader
Verify that an email has a [header](https://datatracker.ietf.org/doc/html/rfc4021) `$headerName`. If the Email object is not specified, the last email sent is used instead.
```
<?php
$I->assertEmailHasHeader('Bcc');
```
### assertEmailHeaderNotSame
Verify that the [header](https://datatracker.ietf.org/doc/html/rfc4021) `$headerName` of an email is not the expected one `$expectedValue`. If the Email object is not specified, the last email sent is used instead.
```
<?php
$I->assertEmailHeaderNotSame('To', '[email protected]');
```
### assertEmailHeaderSame
Verify that the [header](https://datatracker.ietf.org/doc/html/rfc4021) `$headerName` of an email is the same as expected `$expectedValue`. If the Email object is not specified, the last email sent is used instead.
```
<?php
$I->assertEmailHeaderSame('To', '[email protected]');
```
### assertEmailHtmlBodyContains
Verify that the HTML body of an email contains `$text`. If the Email object is not specified, the last email sent is used instead.
```
<?php
$I->assertEmailHtmlBodyContains('Successful registration');
```
### assertEmailHtmlBodyNotContains
Verify that the HTML body of an email does not contain a text `$text`. If the Email object is not specified, the last email sent is used instead.
```
<?php
$I->assertEmailHtmlBodyNotContains('userpassword');
```
### assertEmailNotHasHeader
Verify that an email does not have a [header](https://datatracker.ietf.org/doc/html/rfc4021) `$headerName`. If the Email object is not specified, the last email sent is used instead.
```
<?php
$I->assertEmailNotHasHeader('Bcc');
```
### assertEmailTextBodyContains
Verify the text body of an email contains a `$text`. If the Email object is not specified, the last email sent is used instead.
```
<?php
$I->assertEmailTextBodyContains('Example text body');
```
### assertEmailTextBodyNotContains
Verify that the text body of an email does not contain a `$text`. If the Email object is not specified, the last email sent is used instead.
```
<?php
$I->assertEmailTextBodyNotContains('My secret text body');
```
### attachFile
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
```
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
```
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### click
Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
```
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### deleteHeader
Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
```
* `param string` $name the name of the header to delete.
### dontSee
Checks that the current page doesn’t contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region.
```
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will ignore strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### dontSeeAuthentication
Check that user is not authenticated.
```
<?php
$I->dontSeeAuthentication();
```
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
```
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn’t a cookie with the given name. You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn’t equal the given string. Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
```
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn’t match the given regular expression.
```
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page. You can also specify expected attributes of this element.
```
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeEmailIsSent
Checks that no email was sent. The check is based on `\Symfony\Component\Mailer\EventListener\MessageLoggerListener`, which means: If your app performs a HTTP redirect, you need to suppress it using [stopFollowingRedirects()](symfony#stopFollowingRedirects) first; otherwise this check will *always* pass. Starting with version 2.0.0, `codeception/module-symfony` requires your app to use [Symfony Mailer](https://symfony.com/doc/current/mailer.html). If your app still uses [Swift Mailer](https://symfony.com/doc/current/email.html), set your version constraint to `^1.6`.
### dontSeeEventTriggered
Verifies that one or more event listeners were not called during the test.
```
<?php
$I->dontSeeEventTriggered('App\MyEvent');
$I->dontSeeEventTriggered(new App\Events\MyEvent());
$I->dontSeeEventTriggered(['App\MyEvent', 'App\MyOtherEvent']);
```
* `param string|object|string[]` $expected
### dontSeeFormErrors
Verifies that there are no errors bound to the submitted form.
```
<?php
$I->dontSeeFormErrors();
```
### dontSeeInCurrentUrl
Checks that the current URI doesn’t contain the given string.
```
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### dontSeeInField
Checks that an input field or textarea doesn’t contain the given value. For fuzzy locators, the field is matched by label text, CSS and XPath.
```
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
```
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn’t been assigned any one of many values, an array can be passed as the value:
```
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInSession
Assert that a session attribute does not exist, or is not equal to the passed value.
```
<?php
$I->dontSeeInSession('attribute');
$I->dontSeeInSession('attribute', 'value');
```
* `param string` $attribute
* `param mixed|null` $value
### dontSeeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn’t contain a link with the given string. If the second parameter is given, only links with a matching “href” attribute will be checked.
```
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param string` $text
* `param string` $url optional
### dontSeeOptionIsSelected
Checks that the given option is not selected.
```
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### dontSeeOrphanEvent
Verifies that there were no orphan events during the test.
An orphan event is an event that was triggered by manually executing the [`dispatch()`](https://symfony.com/doc/current/components/event_dispatcher.html#dispatch-the-event) method of the EventDispatcher but was not handled by any listener after it was dispatched.
```
<?php
$I->dontSeeOrphanEvent();
$I->dontSeeOrphanEvent('App\MyEvent');
$I->dontSeeOrphanEvent(new App\Events\MyEvent());
$I->dontSeeOrphanEvent(['App\MyEvent', 'App\MyOtherEvent']);
```
* `param string|object|string[]` $expected
### dontSeeRememberedAuthentication
Check that user is not authenticated with the ‘remember me’ option.
```
<?php
$I->dontSeeRememberedAuthentication();
```
### dontSeeRenderedTemplate
Asserts that a template was not rendered in the response.
```
<?php
$I->dontSeeRenderedTemplate('home.html.twig');
```
* `param string` $template
### dontSeeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->dontSeeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### fillField
Fills a text field or textarea with the given string.
```
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], '[email protected]');
?>
```
* `param` $field
* `param` $value
### followRedirect
Follow pending redirect if there is one.
```
<?php
$I->followRedirect();
```
### goToLogoutPath
Go to the configured logout url (by default: `/logout`). This method includes redirection to the destination page configured after logout.
See the Symfony documentation on [‘Logging Out’](https://symfony.com/doc/current/security.html#logging-out).
### grabAttributeFrom
Grabs the value of the given attribute value from the given element. Fails if element is not found.
```
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabCookie
Grabs a cookie value. You can set additional cookie params like `domain`, `path` in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try `$I->wait(0.1)`.
* `param` $cookie
* `param array` $params
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
```
<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param string` $uri optional
### grabLastSentEmail
Returns the last sent email. The function is based on `\Symfony\Component\Mailer\EventListener\MessageLoggerListener`, which means: If your app performs a HTTP redirect after sending the email, you need to suppress it using [stopFollowingRedirects()](symfony#stopFollowingRedirects) first. Starting with version 2.0.0, `codeception/module-symfony` requires your app to use [Symfony Mailer](https://symfony.com/doc/current/mailer.html). If your app still uses [Swift Mailer](https://symfony.com/doc/current/email.html), set your version constraint to `^1.6`. See also: [grabSentEmails()](symfony#grabSentEmails)
```
<?php
$email = $I->grabLastSentEmail();
$address = $email->getTo()[0];
$I->assertSame('[email protected]', $address->getAddress());
```
* `return \Symfony\Component\Mime\Email|null`
### grabMultiple
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
```
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return string[]`
### grabNumRecords
Retrieves number of records from database ‘id’ is the default search parameter.
```
<?php
$I->grabNumRecords('User::class', ['name' => 'davert']);
```
* `param string` $entityClass The entity class
* `param array` $criteria Optional query criteria
* `return int`
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return string` Current page source code.
### grabParameter
Grabs a Symfony parameter
```
<?php
$I->grabParameter('app.business_name');
```
* `param string` $name
* `return mixed|null`
### grabRepository
Grab a Doctrine entity repository. Works with objects, entities, repositories, and repository interfaces.
```
<?php
$I->grabRepository($user);
$I->grabRepository(User::class);
$I->grabRepository(UserRepository::class);
$I->grabRepository(UserRepositoryInterface::class);
```
* `param object|string` $mixed
* `return \Doctrine\ORM\EntityRepository|null`
### grabSentEmails
Returns an array of all sent emails. The function is based on `\Symfony\Component\Mailer\EventListener\MessageLoggerListener`, which means: If your app performs a HTTP redirect after sending the email, you need to suppress it using [stopFollowingRedirects()](symfony#stopFollowingRedirects) first. Starting with version 2.0.0, `codeception/module-symfony` requires your app to use [Symfony Mailer](https://symfony.com/doc/current/mailer.html). If your app still uses [Swift Mailer](https://symfony.com/doc/current/email.html), set your version constraint to `^1.6`. See also: [grabLastSentEmail()](symfony#grabLastSentEmail)
```
<?php
$emails = $I->grabSentEmails();
```
* `return \Symfony\Component\Mime\Email[]`
### grabService
Grabs a service from the Symfony dependency injection container (DIC). In “test” environment, Symfony uses a special `test.service_container`. See the “[Accessing the Container](https://symfony.com/doc/current/testing.html#accessing-the-container)” documentation. Services that aren’t injected somewhere into your app, need to be defined as `public` to be accessible by Codeception.
```
<?php
$em = $I->grabService('doctrine');
```
* `[Part]` services
* `param string` $serviceId
* `return object`
### grabTextFrom
Finds and returns the text contents of the given element. If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
```
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
* `param` $field
* `return array|mixed|null|string`
### haveHttpHeader
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
```
To use special chars in Header Key use HTML Character Entities: Example: Header with underscore - ‘Client\_Id’ should be represented as - ‘Client\_Id’ or ‘Client\_Id’
```
<?php
$I->haveHttpHeader('Client_Id', 'Codeception');
```
* `param string` $name the name of the request header
* `param string` $value the value to set it to for subsequent requests
### haveServerParameter
Sets SERVER parameter valid for all next requests.
```
$I->haveServerParameter('name', 'value');
```
* `param string` $name
* `param string` $value
### invalidateCachedRouter
Invalidate previously cached routes.
### logout
Alias method for [`logoutProgrammatically()`](symfony#logoutProgrammatically)
```
<?php
$I->logout();
```
### logoutProgrammatically
Invalidates the current user’s session and expires the session cookies. This method does not include any redirects after logging out.
```
<?php
$I->logoutProgrammatically();
```
### makeHtmlSnapshot
Use this method within an [interactive pause](../02-gettingstarted#Interactive-Pause) to save the HTML source code of the current page.
```
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
```
* `param null` $name
### moveBack
Moves back in history.
* `param int` $numberOfSteps (default value 1)
### persistPermanentService
Get service $serviceName and add it to the lists of persistent services, making that service persistent between tests.
* `[Part]` services
* `param string` $serviceName
### persistService
Get service $serviceName and add it to the lists of persistent services.
* `[Part]` services
* `param string` $serviceName
### rebootClientKernel
Reboot client’s kernel. Can be used to manually reboot kernel when ‘rebootable\_client’ => false
```
<?php
// Perform some requests
$I->rebootClientKernel();
// Perform other requests
```
### resetCookie
Unsets cookie with the given name. You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### runSymfonyConsoleCommand
Run Symfony console command, grab response and return as string. Recommended to use for integration or functional testing.
```
<?php
$result = $I->runSymfonyConsoleCommand('hello:world', ['arg' => 'argValue', 'opt1' => 'optValue'], ['input']);
```
* `param string` $command The console command to execute
* `param array` $parameters Parameters (arguments and options) to pass to the command
* `param array` $consoleInputs Console inputs (e.g. used for interactive questions)
* `param int` $expectedExitCode The expected exit code of the command
* `return string` Returns the console output of the command
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.
```
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->see('strong')` will return true for strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### seeAuthentication
Checks that a user is authenticated.
```
<?php
$I->seeAuthentication();
```
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
```
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set. You can set additional cookie params like `domain`, `path` as array passed in last argument.
```
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentActionIs
Checks that current page matches action
```
<?php
$I->seeCurrentActionIs('PostController::index');
$I->seeCurrentActionIs('HomeController');
```
* `param string` $action
### seeCurrentRouteIs
Checks that current url matches route.
```
<?php
$I->seeCurrentRouteIs('posts.index');
$I->seeCurrentRouteIs('posts.show', ['id' => 8]);
```
* `param string` $routeName
* `param array` $params
### seeCurrentTemplateIs
Asserts that the current template matches the expected template.
```
<?php
$I->seeCurrentTemplateIs('home.html.twig');
```
* `param string` $expectedTemplate
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string. Unlike `seeInCurrentUrl`, this only matches the full URL.
```
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
```
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### seeElement
Checks that the given element exists on the page and is visible. You can also specify expected attributes of this element.
```
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
### seeEmailIsSent
Checks if the given number of emails was sent (default `$expectedCount`: 1). The check is based on `\Symfony\Component\Mailer\EventListener\MessageLoggerListener`, which means: If your app performs a HTTP redirect after sending the email, you need to suppress it using [stopFollowingRedirects()](symfony#stopFollowingRedirects) first. Starting with version 2.0.0, `codeception/module-symfony` requires your app to use [Symfony Mailer](https://symfony.com/doc/current/mailer.html). If your app still uses [Swift Mailer](https://symfony.com/doc/current/email.html), set your version constraint to `^1.6`.
```
<?php
$I->seeEmailIsSent(2);
```
* `param int` $expectedCount The expected number of emails sent
### seeEventTriggered
Verifies that one or more event listeners were called during the test.
```
<?php
$I->seeEventTriggered('App\MyEvent');
$I->seeEventTriggered(new App\Events\MyEvent());
$I->seeEventTriggered(['App\MyEvent', 'App\MyOtherEvent']);
```
* `param string|object|string[]` $expected
### seeFormErrorMessage
Verifies that a form field has an error. You can specify the expected error message as second parameter.
```
<?php
$I->seeFormErrorMessage('username');
$I->seeFormErrorMessage('username', 'Username is empty');
```
* `param string` $field
* `param string|null` $message
### seeFormErrorMessages
Verifies that multiple fields on a form have errors.
If you only specify the name of the fields, this method will verify that the field contains at least one error of any type:
```
<?php
$I->seeFormErrorMessages(['telephone', 'address']);
```
If you want to specify the error messages, you can do so by sending an associative array instead, with the key being the name of the field and the error message the value.
This method will validate that the expected error message is contained in the actual error message, that is, you can specify either the entire error message or just a part of it:
```
<?php
$I->seeFormErrorMessages([
'address' => 'The address is too long'
'telephone' => 'too short', // the full error message is 'The telephone is too short'
]);
```
If you don’t want to specify the error message for some fields, you can pass `null` as value instead of the message string, or you can directly omit the value of that field. If that is the case, it will be validated that that field has at least one error of any type:
```
<?php
$I->seeFormErrorMessages([
'telephone' => 'too short',
'address' => null,
'postal code',
]);
```
* `param string[]` $expectedErrors
### seeFormHasErrors
Verifies that there are one or more errors bound to the submitted form.
```
<?php
$I->seeFormHasErrors();
```
### seeInCurrentRoute
Checks that current url matches route. Unlike seeCurrentRouteIs, this can matches without exact route parameters
```
<?php
$I->seeInCurrentRoute('my_blog_pages');
```
* `param string` $routeName
### seeInCurrentUrl
Checks that current URI contains the given string.
```
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### seeInField
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value. Fields are matched by label text, the “name” attribute, CSS, or XPath.
```
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
```
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
```
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInSession
Assert that a session attribute exists.
```
<?php
$I->seeInSession('attribute');
$I->seeInSession('attribute', 'value');
```
* `param string` $attribute
* `param mixed|null` $value
### seeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
```
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there’s a link with the specified text. Give a full URL as the second parameter to match links with that exact URL.
```
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param string` $text
* `param string` $url optional
### seeNumRecords
Checks that number of given records were found in database. ‘id’ is the default search parameter.
```
<?php
$I->seeNumRecords(1, User::class, ['name' => 'davert']);
$I->seeNumRecords(80, User::class);
```
* `param int` $expectedNum Expected number of records
* `param string` $className A doctrine entity
* `param array` $criteria Optional query criteria
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
```
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected int or int[]
### seeOptionIsSelected
Checks that the given option is selected.
```
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### seeOrphanEvent
Verifies that one or more orphan events were dispatched during the test.
An orphan event is an event that was triggered by manually executing the [`dispatch()`](https://symfony.com/doc/current/components/event_dispatcher.html#dispatch-the-event) method of the EventDispatcher but was not handled by any listener after it was dispatched.
```
<?php
$I->seeOrphanEvent('App\MyEvent');
$I->seeOrphanEvent(new App\Events\MyEvent());
$I->seeOrphanEvent(['App\MyEvent', 'App\MyOtherEvent']);
```
* `param string|object|string[]` $expected
### seePageIsAvailable
Verifies that a page is available. By default it checks the current page, specify the `$url` parameter to change it.
```
<?php
$I->amOnPage('/dashboard');
$I->seePageIsAvailable();
$I->seePageIsAvailable('/dashboard'); // Same as above
```
* `param string|null` $url
### seePageNotFound
Asserts that current page has 404 response status code.
### seePageRedirectsTo
Goes to a page and check that it redirects to another.
```
<?php
$I->seePageRedirectsTo('/admin', '/login');
```
* `param string` $page
* `param string` $redirectsTo
### seeRememberedAuthentication
Checks that a user is authenticated with the ‘remember me’ option.
```
<?php
$I->seeRememberedAuthentication();
```
### seeRenderedTemplate
Asserts that a template was rendered in the response. That includes templates built with [inheritance](https://twig.symfony.com/doc/3.x/templates.html#template-inheritance).
```
<?php
$I->seeRenderedTemplate('home.html.twig');
$I->seeRenderedTemplate('layout.html.twig');
```
* `param string` $template
### seeRequestTimeIsLessThan
Asserts that the time a request lasted is less than expected.
If the page performed a HTTP redirect, only the time of the last request will be taken into account. You can modify this behavior using [stopFollowingRedirects()](symfony#stopFollowingRedirects) first.
Also, note that using code coverage can significantly increase the time it takes to resolve a request, which could lead to unreliable results when used together.
It is recommended to set [`rebootable_client`](symfony#Config) to `true` (=default), cause otherwise this assertion gives false results if you access multiple pages in a row, or if your app performs a redirect.
* `param int|float` $expectedMilliseconds The expected time in milliseconds
### seeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->seeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### seeResponseCodeIsBetween
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
* `param int` $from
* `param int` $to
### seeResponseCodeIsClientError
Checks that the response code is 4xx
### seeResponseCodeIsRedirection
Checks that the response code 3xx
### seeResponseCodeIsServerError
Checks that the response code is 5xx
### seeResponseCodeIsSuccessful
Checks that the response code 2xx
### seeSessionHasValues
Assert that the session has a given list of values.
```
<?php
$I->seeSessionHasValues(['key1', 'key2']);
$I->seeSessionHasValues(['key1' => 'value1', 'key2' => 'value2']);
```
* `param array` $bindings
### seeUserHasRole
Check that the current user has a role
```
<?php
$I->seeUserHasRole('ROLE_ADMIN');
```
* `param string` $role
### seeUserHasRoles
Verifies that the current user has multiple roles
```
<?php
$I->seeUserHasRoles(['ROLE_USER', 'ROLE_ADMIN']);
```
* `param string[]` $roles
### seeUserPasswordDoesNotNeedRehash
Checks that the user’s password would not benefit from rehashing. If the user is not provided it is taken from the current session.
You might use this function after performing tasks like registering a user or submitting a password update form.
```
<?php
$I->seeUserPasswordDoesNotNeedRehash();
$I->seeUserPasswordDoesNotNeedRehash($user);
```
* `param UserInterface|null` $user
### selectOption
Selects an option in a select tag or in radio button group.
```
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
```
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
```
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### sendAjaxGetRequest
Sends an ajax GET request with the passed parameters. See `sendAjaxPostRequest()`
* `param` $uri
* `param` $params
### sendAjaxPostRequest
Sends an ajax POST request with the passed parameters. The appropriate HTTP header is added automatically: `X-Requested-With: XMLHttpRequest` Example:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['task' => 'lorem ipsum']);
```
Some frameworks (e.g. Symfony) create field names in the form of an “array”: `<input type="text" name="form[task]">` In this case you need to pass the fields like this:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['form' => [
'task' => 'lorem ipsum',
'category' => 'miscellaneous',
]]);
```
* `param string` $uri
* `param array` $params
### sendAjaxRequest
Sends an ajax request, using the passed HTTP method. See `sendAjaxPostRequest()` Example:
```
<?php
$I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
```
* `param` $method
* `param` $uri
* `param array` $params
### setCookie
Sets a cookie with the given name and value. You can set additional cookie params like `domain`, `path`, `expires`, `secure` in array passed as last argument.
```
<?php
$I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
?>
```
* `param` $name
* `param` $val
* `param array` $params
### setMaxRedirects
Sets the maximum number of redirects that the Client can follow.
```
<?php
$I->setMaxRedirects(2);
```
* `param int` $maxRedirects
### setServerParameters
Sets SERVER parameters valid for all next requests. this will remove old ones.
```
$I->setServerParameters([]);
```
### startFollowingRedirects
Enables automatic redirects to be followed by the client.
```
<?php
$I->startFollowingRedirects();
```
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client.
```
<?php
$I->stopFollowingRedirects();
```
### submitForm
Submits the given form on the page, with the given form values. Pass the form field’s values as an array in the second parameter.
Although this function can be used as a short-hand version of `fillField()`, `selectOption()`, `click()` etc. it has some important differences:
* Only field *names* may be used, not CSS/XPath selectors nor field labels
* If a field is sent to this function that does *not* exist on the page, it will silently be added to the HTTP request. This is helpful for testing some types of forms, but be aware that you will *not* get an exception like you would if you called `fillField()` or `selectOption()` with a missing field.
Fields that are not provided will be filled by their values from the page, or from any previous calls to `fillField()`, `selectOption()` etc. You don’t need to click the ‘Submit’ button afterwards. This command itself triggers the request to form’s action.
You can optionally specify which button’s value to include in the request with the last parameter (as an alternative to explicitly setting its value in the second parameter), as button values are not otherwise included in the request.
Examples:
```
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample “Sign Up” form:
```
<form id="userForm">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Subscribe to our newsletter?
<input type="checkbox" name="user[newsletter]" value="1" checked="checked" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
],
'submitButton'
);
```
Note that “2” will be the submitted value for the “plan” field, as it is the selected option.
To uncheck the pre-checked checkbox “newsletter”, call `$I->uncheckOption(['name' => 'user[newsletter]']);` *before*, then submit the form as shown here (i.e. without the “newsletter” field in the `$params` array).
You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
]
);
```
This function works well when paired with `seeInFormFields()` for quickly testing CRUD interfaces and form validation logic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);
```
Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean `true`/`false` which will be replaced by the checkbox’s value in the DOM.
```
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false
],
'multiselect' => [
'first option value',
'second option value'
]
]);
```
Mixing string and boolean values for a checkbox’s value is not supported and may produce unexpected results.
Field names ending in `[]` must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:
```
<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```
<?php
// This way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
* `param` $selector
* `param` $params
* `param` $button
### submitSymfonyForm
Submit a form specifying the form name only once.
Use this function instead of [`$I->submitForm()`](#submitForm) to avoid repeating the form name in the field selectors. If you customized the names of the field selectors use `$I->submitForm()` for full control.
```
<?php
$I->submitSymfonyForm('login_form', [
'[email]' => '[email protected]',
'[password]' => 'secretForest'
]);
```
* `param string` $name The `name` attribute of the `<form>` (you cannot use an array as selector here)
* `param string[]` $fields
### switchToIframe
Switch to iframe or frame on the page.
Example:
```
<iframe name="another_frame" src="http://example.com">
```
```
<?php
# switch to iframe
$I->switchToIframe("another_frame");
```
* `param string` $name
### uncheckOption
Unticks a checkbox.
```
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
### unpersistService
Remove service $serviceName from the lists of persistent services.
* `[Part]` services
* `param string` $serviceName
| programming_docs |
codeception Laravel Laravel
=======
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-laravel
```
Alternatively, you can enable `Laravel` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module allows you to run functional tests for Laravel 6.0+ It should **not** be used for acceptance tests. See the Acceptance tests section below for more details.
Demo project
------------
<https://github.com/Codeception/laravel-module-tests>
Config
------
* cleanup: `boolean`, default `true` - all database queries will be run in a transaction, which will be rolled back at the end of each test.
* run\_database\_migrations: `boolean`, default `false` - run database migrations before each test.
* database\_migrations\_path: `string`, default `null` - path to the database migrations, relative to the root of the application.
* run\_database\_seeder: `boolean`, default `false` - run database seeder before each test.
* database\_seeder\_class: `string`, default `` - database seeder class name.
* environment\_file: `string`, default `.env` - the environment file to load for the tests.
* bootstrap: `string`, default `bootstrap/app.php` - relative path to app.php config file.
* root: `string`, default `` - root path of the application.
* packages: `string`, default `workbench` - root path of application packages (if any).
* vendor\_dir: `string`, default `vendor` - optional relative path to vendor directory.
* disable\_exception\_handling: `boolean`, default `true` - disable Laravel exception handling.
* disable\_middleware: `boolean`, default `false` - disable all middleware.
* disable\_events: `boolean`, default `false` - disable events (does not disable model events).
* disable\_model\_events: `boolean`, default `false` - disable model events.
* url: `string`, default `` - the application URL.
### Example #1 (`functional.suite.yml`)
Enabling module:
```
yml
modules:
enabled:
- Laravel
```
### Example #2 (`functional.suite.yml`)
Enabling module with custom .env file
```
yml
modules:
enabled:
- Laravel:
environment_file: .env.testing
```
API
---
* app - `Illuminate\Foundation\Application`
* config - `array`
Parts
-----
* `ORM`: Only include the database methods of this module:
+ dontSeeRecord
+ grabNumRecords
+ grabRecord
+ have
+ haveMultiple
+ haveRecord
+ make
+ makeMultiple
+ seedDatabase
+ seeNumRecords
+ seeRecord
See [WebDriver module](webdriver#Loading-Parts-from-other-Modules) for general information on how to load parts of a framework module.
Acceptance tests
----------------
You should not use this module for acceptance tests. If you want to use Eloquent within your acceptance tests (paired with WebDriver) enable only ORM part of this module:
### Example (`acceptance.suite.yml`)
```
modules:
enabled:
- WebDriver:
browser: chrome
url: http://127.0.0.1:8000
- Laravel:
part: ORM
environment_file: .env.testing
```
Actions
-------
### \_findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$els = $this->getModule('Laravel')->_findElements('.items');
$els = $this->getModule('Laravel')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('Laravel')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return array` of interactive elements
### \_getResponseContent
*hidden API method, expected to be used from Helper classes*
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
```
<?php
// in Helper class
public function seeResponseContains($text)
{
$this->assertStringContainsString($text, $this->getModule('Laravel')->_getResponseContent(), "response contains");
}
```
* `return string` @throws ModuleException
### \_loadPage
*hidden API method, expected to be used from Helper classes*
Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step.
```
<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
$this->getModule('Laravel')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
```
* `param string` $method
* `param string` $uri
* `param string` $content
### \_request
*hidden API method, expected to be used from Helper classes*
Send custom request to a backend using method, uri, parameters, etc. Use it in Helpers to create special request actions, like accessing API Returns a string with response body.
```
<?php
// in Helper class
public function createUserByApi($name) {
$userData = $this->getModule('Laravel')->_request('POST', '/api/v1/users', ['name' => $name]);
$user = json_decode($userData);
return $user->id;
}
```
Does not load the response into the module so you can’t interact with response page (click, fill forms). To load arbitrary page for interaction, use `_loadPage` method.
* `param string` $method
* `param string` $uri
* `param string` $content
* `return string` @throws ExternalUrlException @see `_loadPage`
### \_savePageSource
*hidden API method, expected to be used from Helper classes*
Saves page source of to a file
```
$this->getModule('Laravel')->_savePageSource(codecept_output_dir().'page.html');
```
* `param` $filename
### amActingAs
Set the given user object to the current or specified Guard.
```
<?php
$I->amActingAs($user);
```
### amHttpAuthenticated
Authenticates user for HTTP\_AUTH
* `param string` $username
* `param string` $password
### amLoggedAs
Set the currently logged in user for the application. Unlike ‘amActingAs’, this method does update the session, fire the login events and remember the user as it assigns the corresponding Cookie.
```
<?php
// provide array of credentials
$I->amLoggedAs(['username' => '[email protected]', 'password' => 'password']);
// provide User object that implements the User interface
$I->amLoggedAs( new User );
// can be verified with $I->seeAuthentication();
```
* `param Authenticatable|array` $user
* `param string|null` $guardName
### amOnAction
Opens web page by action name
```
<?php
// Laravel 6 or 7:
$I->amOnAction('PostsController@index');
// Laravel 8+:
$I->amOnAction(PostsController::class . '@index');
```
* `param string` $action
* `param mixed` $parameters
### amOnPage
Opens the page for the given relative URI.
```
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
```
* `param string` $page
### amOnRoute
Opens web page using route name and parameters.
```
<?php
$I->amOnRoute('posts.create');
```
* `param string` $routeName
* `param mixed` $params
### assertAuthenticatedAs
Assert that the user is authenticated as the given user.
```
<?php
$I->assertAuthenticatedAs($user);
```
### assertCredentials
Assert that the given credentials are valid.
```
<?php
$I->assertCredentials([
'email' => '[email protected]',
'password' => '123456'
]);
```
### assertInvalidCredentials
Assert that the given credentials are invalid.
```
<?php
$I->assertInvalidCredentials([
'email' => '[email protected]',
'password' => 'wrong_password'
]);
```
### attachFile
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
```
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### callArtisan
Call an Artisan command.
```
<?php
$I->callArtisan('command:name');
$I->callArtisan('command:name', ['parameter' => 'value']);
```
Use 3rd parameter to pass in custom `OutputInterface`
* `return string|void`
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
```
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### clearApplicationHandlers
Clear the registered application handlers.
```
<?php
$I->clearApplicationHandlers();
```
### click
Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
```
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### deleteHeader
Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
```
* `param string` $name the name of the header to delete.
### disableEvents
Disable events for the next requests. This method does not disable model events. To disable model events you have to use the disableModelEvents() method.
```
<?php
$I->disableEvents();
```
### disableExceptionHandling
Disable Laravel exception handling.
```
<?php
$I->disableExceptionHandling();
```
### disableMiddleware
Disable middleware for the next requests.
```
<?php
$I->disableMiddleware();
```
* `param string|array|null` $middleware
### disableModelEvents
Disable model events for the next requests.
```
<?php
$I->disableModelEvents();
```
### dontSee
Checks that the current page doesn’t contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region.
```
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will ignore strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### dontSeeAuthentication
Check that user is not authenticated.
```
<?php
$I->dontSeeAuthentication();
```
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
```
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn’t a cookie with the given name. You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn’t equal the given string. Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
```
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn’t match the given regular expression.
```
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page. You can also specify expected attributes of this element.
```
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeEventTriggered
Make sure events did not fire during the test.
```
<?php
$I->dontSeeEventTriggered('App\MyEvent');
$I->dontSeeEventTriggered(new App\Events\MyEvent());
$I->dontSeeEventTriggered(['App\MyEvent', 'App\MyOtherEvent']);
```
* `param string|object|string[]` $expected
### dontSeeFormErrors
Assert that there are no form errors bound to the View.
```
<?php
$I->dontSeeFormErrors();
```
### dontSeeInCurrentUrl
Checks that the current URI doesn’t contain the given string.
```
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### dontSeeInField
Checks that an input field or textarea doesn’t contain the given value. For fuzzy locators, the field is matched by label text, CSS and XPath.
```
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
```
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn’t been assigned any one of many values, an array can be passed as the value:
```
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInSession
Assert that a session attribute does not exist, or is not equal to the passed value.
```
<?php
$I->dontSeeInSession('attribute');
$I->dontSeeInSession('attribute', 'value');
```
* `param string|array` $key
* `param mixed|null` $value
### dontSeeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn’t contain a link with the given string. If the second parameter is given, only links with a matching “href” attribute will be checked.
```
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param string` $text
* `param string` $url optional
### dontSeeOptionIsSelected
Checks that the given option is not selected.
```
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### dontSeeRecord
Checks that record does not exist in database. You can pass the name of a database table or the class name of an Eloquent model as the first argument.
```
<?php
$I->dontSeeRecord($user);
$I->dontSeeRecord('users', ['name' => 'Davert']);
$I->dontSeeRecord('App\Models\User', ['name' => 'Davert']);
```
* `param string|class-string|object` $table
* `param array` $attributes
* `[Part]` orm
### dontSeeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->dontSeeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### dontSeeSessionHasValues
Assert that the session does not have a particular list of values.
```
<?php
$I->dontSeeSessionHasValues(['key1', 'key2']);
$I->dontSeeSessionHasValues(['key1' => 'value1', 'key2' => 'value2']);
```
### enableExceptionHandling
Enable Laravel exception handling.
```
<?php
$I->enableExceptionHandling();
```
### enableMiddleware
Enable the given middleware for the next requests.
```
<?php
$I->enableMiddleware();
```
* `param string|array|null` $middleware
### fillField
Fills a text field or textarea with the given string.
```
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], '[email protected]');
?>
```
* `param` $field
* `param` $value
### flushSession
Flush all of the current session data.
```
<?php
$I->flushSession();
```
### followRedirect
Follow pending redirect if there is one.
```
<?php
$I->followRedirect();
```
### getApplication
Provides access the Laravel application object.
```
<?php
$app = $I->getApplication();
```
### grabAttributeFrom
Grabs the value of the given attribute value from the given element. Fails if element is not found.
```
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabCookie
Grabs a cookie value. You can set additional cookie params like `domain`, `path` in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try `$I->wait(0.1)`.
* `param` $cookie
* `param array` $params
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
```
<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param string` $uri optional
### grabMultiple
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
```
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return string[]`
### grabNumRecords
Retrieves number of records from database You can pass the name of a database table or the class name of an Eloquent model as the first argument.
```
<?php
$I->grabNumRecords('users', ['name' => 'Davert']);
$I->grabNumRecords('App\Models\User', ['name' => 'Davert']);
```
* `[Part]` orm
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return string` Current page source code.
### grabRecord
Retrieves record from database If you pass the name of a database table as the first argument, this method returns an array. You can also pass the class name of an Eloquent model, in that case this method returns an Eloquent model.
```
<?php
$record = $I->grabRecord('users', ['name' => 'Davert']); // returns array
$record = $I->grabRecord('App\Models\User', ['name' => 'Davert']); // returns Eloquent model
```
* `param string` $table
* `param array` $attributes
* `return array|EloquentModel`
* `[Part]` orm
### grabService
Return an instance of a class from the Laravel service container. (https://laravel.com/docs/7.x/container)
```
<?php
// In Laravel
App::bind('foo', function($app) {
return new FooBar;
});
// Then in test
$service = $I->grabService('foo');
// Will return an instance of FooBar, also works for singletons.
```
### grabTextFrom
Finds and returns the text contents of the given element. If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
```
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
* `param` $field
* `return array|mixed|null|string`
### have
Use Laravel model factory to create a model.
```
<?php
$I->have('App\Models\User');
$I->have('App\Models\User', ['name' => 'John Doe']);
$I->have('App\Models\User', [], 'admin');
```
@see https://laravel.com/docs/7.x/database-testing#using-factories
* `[Part]` orm
### haveApplicationHandler
Register a handler than can be used to modify the Laravel application object after it is initialized. The Laravel application object will be passed as an argument to the handler.
```
<?php
$I->haveApplicationHandler(function($app) {
$app->make('config')->set(['test_value' => '10']);
});
```
### haveBinding
Add a binding to the Laravel service container. (https://laravel.com/docs/7.x/container)
```
<?php
$I->haveBinding('My\Interface', 'My\Implementation');
```
* `param string` $abstract
* `param Closure|string|null` $concrete
* `param bool` $shared
### haveContextualBinding
Add a contextual binding to the Laravel service container. (https://laravel.com/docs/7.x/container)
```
<?php
$I->haveContextualBinding('My\Class', '$variable', 'value');
// This is similar to the following in your Laravel application
$app->when('My\Class')
->needs('$variable')
->give('value');
```
* `param string` $concrete
* `param string` $abstract
* `param Closure|string` $implementation
### haveHttpHeader
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
```
To use special chars in Header Key use HTML Character Entities: Example: Header with underscore - ‘Client\_Id’ should be represented as - ‘Client\_Id’ or ‘Client\_Id’
```
<?php
$I->haveHttpHeader('Client_Id', 'Codeception');
```
* `param string` $name the name of the request header
* `param string` $value the value to set it to for subsequent requests
### haveInSession
Set the session to the given array.
```
<?php
$I->haveInSession(['myKey' => 'MyValue']);
```
### haveInstance
Add an instance binding to the Laravel service container. (https://laravel.com/docs/7.x/container)
```
<?php
$I->haveInstance('App\MyClass', new App\MyClass());
```
### haveMultiple
Use Laravel model factory to create multiple models.
```
<?php
$I->haveMultiple('App\Models\User', 10);
$I->haveMultiple('App\Models\User', 10, ['name' => 'John Doe']);
$I->haveMultiple('App\Models\User', 10, [], 'admin');
```
@see https://laravel.com/docs/7.x/database-testing#using-factories
* `return EloquentModel|EloquentCollection`
* `[Part]` orm
### haveRecord
Inserts record into the database. If you pass the name of a database table as the first argument, this method returns an integer ID. You can also pass the class name of an Eloquent model, in that case this method returns an Eloquent model.
```
<?php
$user_id = $I->haveRecord('users', ['name' => 'Davert']); // returns integer
$user = $I->haveRecord('App\Models\User', ['name' => 'Davert']); // returns Eloquent model
```
* `param string` $table
* `param array` $attributes
* `return EloquentModel|int` @throws RuntimeException
* `[Part]` orm
### haveServerParameter
Sets SERVER parameter valid for all next requests.
```
$I->haveServerParameter('name', 'value');
```
* `param string` $name
* `param string` $value
### haveSingleton
Add a singleton binding to the Laravel service container. (https://laravel.com/docs/7.x/container)
```
<?php
$I->haveSingleton('App\MyInterface', 'App\MySingleton');
```
* `param string` $abstract
* `param Closure|string|null` $concrete
### logout
Logout user.
```
<?php
$I->logout();
```
### make
Use Laravel model factory to make a model instance.
```
<?php
$I->make('App\Models\User');
$I->make('App\Models\User', ['name' => 'John Doe']);
$I->make('App\Models\User', [], 'admin');
```
@see https://laravel.com/docs/7.x/database-testing#using-factories
* `return EloquentCollection|EloquentModel`
* `[Part]` orm
### makeHtmlSnapshot
Use this method within an [interactive pause](../02-gettingstarted#Interactive-Pause) to save the HTML source code of the current page.
```
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
```
* `param null` $name
### makeMultiple
Use Laravel model factory to make multiple model instances.
```
<?php
$I->makeMultiple('App\Models\User', 10);
$I->makeMultiple('App\Models\User', 10, ['name' => 'John Doe']);
$I->makeMultiple('App\Models\User', 10, [], 'admin');
```
@see https://laravel.com/docs/7.x/database-testing#using-factories
* `return EloquentCollection|EloquentModel`
* `[Part]` orm
### moveBack
Moves back in history.
* `param int` $numberOfSteps (default value 1)
### resetCookie
Unsets cookie with the given name. You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.
```
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->see('strong')` will return true for strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### seeAuthentication
Checks that a user is authenticated.
```
<?php
$I->seeAuthentication();
```
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
```
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set. You can set additional cookie params like `domain`, `path` as array passed in last argument.
```
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentActionIs
Checks that current url matches action
```
<?php
// Laravel 6 or 7:
$I->seeCurrentActionIs('PostsController@index');
// Laravel 8+:
$I->seeCurrentActionIs(PostsController::class . '@index');
```
### seeCurrentRouteIs
Checks that current url matches route
```
<?php
$I->seeCurrentRouteIs('posts.index');
```
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string. Unlike `seeInCurrentUrl`, this only matches the full URL.
```
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
```
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### seeElement
Checks that the given element exists on the page and is visible. You can also specify expected attributes of this element.
```
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
### seeEventTriggered
Make sure events fired during the test.
```
<?php
$I->seeEventTriggered('App\MyEvent');
$I->seeEventTriggered(new App\Events\MyEvent());
$I->seeEventTriggered(['App\MyEvent', 'App\MyOtherEvent']);
```
* `param string|object|string[]` $expected
### seeFormErrorMessage
Assert that a specific form error message is set in the view.
If you want to assert that there is a form error message for a specific key but don’t care about the actual error message you can omit `$expectedErrorMessage`.
If you do pass `$expectedErrorMessage`, this method checks if the actual error message for a key contains `$expectedErrorMessage`.
```
<?php
$I->seeFormErrorMessage('username');
$I->seeFormErrorMessage('username', 'Invalid Username');
```
### seeFormErrorMessages
Verifies that multiple fields on a form have errors.
This method will validate that the expected error message is contained in the actual error message, that is, you can specify either the entire error message or just a part of it:
```
<?php
$I->seeFormErrorMessages([
'address' => 'The address is too long',
'telephone' => 'too short' // the full error message is 'The telephone is too short'
]);
```
If you don’t want to specify the error message for some fields, you can pass `null` as value instead of the message string. If that is the case, it will be validated that that field has at least one error of any type:
```
<?php
$I->seeFormErrorMessages([
'telephone' => 'too short',
'address' => null
]);
```
### seeFormHasErrors
Assert that form errors are bound to the View.
```
<?php
$I->seeFormHasErrors();
```
### seeInCurrentUrl
Checks that current URI contains the given string.
```
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### seeInField
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value. Fields are matched by label text, the “name” attribute, CSS, or XPath.
```
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
```
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
```
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInSession
Assert that a session variable exists.
```
<?php
$I->seeInSession('key');
$I->seeInSession('key', 'value');
```
* `param string|array` $key
* `param mixed|null` $value
### seeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
```
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there’s a link with the specified text. Give a full URL as the second parameter to match links with that exact URL.
```
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param string` $text
* `param string` $url optional
### seeNumRecords
Checks that number of given records were found in database. You can pass the name of a database table or the class name of an Eloquent model as the first argument.
```
<?php
$I->seeNumRecords(1, 'users', ['name' => 'Davert']);
$I->seeNumRecords(1, 'App\Models\User', ['name' => 'Davert']);
```
* `[Part]` orm
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
```
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected int or int[]
### seeOptionIsSelected
Checks that the given option is selected.
```
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### seePageNotFound
Asserts that current page has 404 response status code.
### seeRecord
Checks that record exists in database. You can pass the name of a database table or the class name of an Eloquent model as the first argument.
```
<?php
$I->seeRecord($user);
$I->seeRecord('users', ['name' => 'Davert']);
$I->seeRecord('App\Models\User', ['name' => 'Davert']);
```
* `param string|class-string|object` $table
* `param array` $attributes
* `[Part]` orm
### seeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->seeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### seeResponseCodeIsBetween
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
* `param int` $from
* `param int` $to
### seeResponseCodeIsClientError
Checks that the response code is 4xx
### seeResponseCodeIsRedirection
Checks that the response code 3xx
### seeResponseCodeIsServerError
Checks that the response code is 5xx
### seeResponseCodeIsSuccessful
Checks that the response code 2xx
### seeSessionHasValues
Assert that the session has a given list of values.
```
<?php
$I->seeSessionHasValues(['key1', 'key2']);
$I->seeSessionHasValues(['key1' => 'value1', 'key2' => 'value2']);
```
### seedDatabase
Seed a given database connection.
* `param class-string|class-string[]` $seeders
### selectOption
Selects an option in a select tag or in radio button group.
```
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
```
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
```
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### sendAjaxGetRequest
Sends an ajax GET request with the passed parameters. See `sendAjaxPostRequest()`
* `param` $uri
* `param` $params
### sendAjaxPostRequest
Sends an ajax POST request with the passed parameters. The appropriate HTTP header is added automatically: `X-Requested-With: XMLHttpRequest` Example:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['task' => 'lorem ipsum']);
```
Some frameworks (e.g. Symfony) create field names in the form of an “array”: `<input type="text" name="form[task]">` In this case you need to pass the fields like this:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['form' => [
'task' => 'lorem ipsum',
'category' => 'miscellaneous',
]]);
```
* `param string` $uri
* `param array` $params
### sendAjaxRequest
Sends an ajax request, using the passed HTTP method. See `sendAjaxPostRequest()` Example:
```
<?php
$I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
```
* `param` $method
* `param` $uri
* `param array` $params
### setApplication
**not documented**
### setCookie
Sets a cookie with the given name and value. You can set additional cookie params like `domain`, `path`, `expires`, `secure` in array passed as last argument.
```
<?php
$I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
?>
```
* `param` $name
* `param` $val
* `param array` $params
### setMaxRedirects
Sets the maximum number of redirects that the Client can follow.
```
<?php
$I->setMaxRedirects(2);
```
* `param int` $maxRedirects
### setServerParameters
Sets SERVER parameters valid for all next requests. this will remove old ones.
```
$I->setServerParameters([]);
```
### startFollowingRedirects
Enables automatic redirects to be followed by the client.
```
<?php
$I->startFollowingRedirects();
```
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client.
```
<?php
$I->stopFollowingRedirects();
```
### submitForm
Submits the given form on the page, with the given form values. Pass the form field’s values as an array in the second parameter.
Although this function can be used as a short-hand version of `fillField()`, `selectOption()`, `click()` etc. it has some important differences:
* Only field *names* may be used, not CSS/XPath selectors nor field labels
* If a field is sent to this function that does *not* exist on the page, it will silently be added to the HTTP request. This is helpful for testing some types of forms, but be aware that you will *not* get an exception like you would if you called `fillField()` or `selectOption()` with a missing field.
Fields that are not provided will be filled by their values from the page, or from any previous calls to `fillField()`, `selectOption()` etc. You don’t need to click the ‘Submit’ button afterwards. This command itself triggers the request to form’s action.
You can optionally specify which button’s value to include in the request with the last parameter (as an alternative to explicitly setting its value in the second parameter), as button values are not otherwise included in the request.
Examples:
```
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample “Sign Up” form:
```
<form id="userForm">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Subscribe to our newsletter?
<input type="checkbox" name="user[newsletter]" value="1" checked="checked" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
],
'submitButton'
);
```
Note that “2” will be the submitted value for the “plan” field, as it is the selected option.
To uncheck the pre-checked checkbox “newsletter”, call `$I->uncheckOption(['name' => 'user[newsletter]']);` *before*, then submit the form as shown here (i.e. without the “newsletter” field in the `$params` array).
You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
]
);
```
This function works well when paired with `seeInFormFields()` for quickly testing CRUD interfaces and form validation logic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);
```
Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean `true`/`false` which will be replaced by the checkbox’s value in the DOM.
```
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false
],
'multiselect' => [
'first option value',
'second option value'
]
]);
```
Mixing string and boolean values for a checkbox’s value is not supported and may produce unexpected results.
Field names ending in `[]` must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:
```
<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```
<?php
// This way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
* `param` $selector
* `param` $params
* `param` $button
### switchToIframe
Switch to iframe or frame on the page.
Example:
```
<iframe name="another_frame" src="http://example.com">
```
```
<?php
# switch to iframe
$I->switchToIframe("another_frame");
```
* `param string` $name
### uncheckOption
Unticks a checkbox.
```
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
| programming_docs |
codeception Yii2 Yii2
====
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-yii2
```
Alternatively, you can enable `Yii2` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module provides integration with [Yii framework](http://www.yiiframework.com/) (2.0).
It initializes the Yii framework in a test environment and provides actions for functional testing.
Application state during testing
--------------------------------
This section details what you can expect when using this module.
* You will get a fresh application in `\Yii::$app` at the start of each test (available in the test and in `_before()`).
* Inside your test you may change application state; however these changes will be lost when doing a request if you have enabled `recreateApplication`.
* When executing a request via one of the request functions the `request` and `response` component are both recreated.
* After a request the whole application is available for inspection / interaction.
* You may use multiple database connections, each will use a separate transaction; to prevent accidental mistakes we will warn you if you try to connect to the same database twice but we cannot reuse the same connection.
Config
------
* `configFile` *required* - path to the application config file. The file should be configured for the test environment and return a configuration array.
* `applicationClass` - Fully qualified class name for the application. There are several ways to define the application class. Either via a `class` key in the Yii config, via specifying this codeception module configuration value or let codeception use its default value `yii\web\Application`. In a standard Yii application, this value should be either `yii\console\Application`, `yii\web\Application` or unset.
* `entryUrl` - initial application url (default: http://localhost/index-test.php).
* `entryScript` - front script title (like: index-test.php). If not set it’s taken from `entryUrl`.
* `transaction` - (default: `true`) wrap all database connection inside a transaction and roll it back after the test. Should be disabled for acceptance testing.
* `cleanup` - (default: `true`) cleanup fixtures after the test
* `ignoreCollidingDSN` - (default: `false`) When 2 database connections use the same DSN but different settings an exception will be thrown. Set this to true to disable this behavior.
* `fixturesMethod` - (default: `_fixtures`) Name of the method used for creating fixtures.
* `responseCleanMethod` - (default: `clear`) Method for cleaning the response object. Note that this is only for multiple requests inside a single test case. Between test cases the whole application is always recreated.
* `requestCleanMethod` - (default: `recreate`) Method for cleaning the request object. Note that this is only for multiple requests inside a single test case. Between test cases the whole application is always recreated.
* `recreateComponents` - (default: `[]`) Some components change their state making them unsuitable for processing multiple requests. In production this is usually not a problem since web apps tend to die and start over after each request. This allows you to list application components that need to be recreated before each request. As a consequence, any components specified here should not be changed inside a test since those changes will get discarded.
* `recreateApplication` - (default: `false`) whether to recreate the whole application before each request
You can use this module by setting params in your `functional.suite.yml`:
```
actor: FunctionalTester
modules:
enabled:
- Yii2:
configFile: 'path/to/config.php'
```
Parts
-----
By default all available methods are loaded, but you can also use the `part` option to select only the needed actions and to avoid conflicts. The available parts are:
* `init` - use the module only for initialization (for acceptance tests).
* `orm` - include only `haveRecord/grabRecord/seeRecord/dontSeeRecord` actions.
* `fixtures` - use fixtures inside tests with `haveFixtures/grabFixture/grabFixtures` actions.
* `email` - include email actions `seeEmailsIsSent/grabLastSentEmail/...`
See [WebDriver module](webdriver#Loading-Parts-from-other-Modules) for general information on how to load parts of a framework module.
### Example (`acceptance.suite.yml`)
```
actor: AcceptanceTester
modules:
enabled:
- WebDriver:
url: http://127.0.0.1:8080/
browser: firefox
- Yii2:
configFile: 'config/test.php'
part: orm # allow to use AR methods
transaction: false # don't wrap test in transaction
cleanup: false # don't cleanup the fixtures
entryScript: index-test.php
```
Fixtures
--------
This module allows to use [fixtures](http://www.yiiframework.com/doc-2.0/guide-test-fixtures.html) inside a test. There are two ways to do that. Fixtures can either be loaded with the [haveFixtures](#haveFixtures) method inside a test:
```
<?php
$I->haveFixtures(['posts' => PostsFixture::className()]);
```
or, if you need to load fixtures before the test, you can specify fixtures in the `_fixtures` method of a test case:
```
<?php
// inside Cest file or Codeception\TestCase\Unit
public function _fixtures()
{
return ['posts' => PostsFixture::className()]
}
```
URL
---
With this module you can also use Yii2’s URL format for all codeception commands that expect a URL:
```
<?php
$I->amOnPage(['site/view','page'=>'about']);
$I->amOnPage('index-test.php?site/index');
$I->amOnPage('http://localhost/index-test.php?site/index');
$I->sendAjaxPostRequest(['/user/update', 'id' => 1], ['UserForm[name]' => 'G.Hopper']);
```
Status
------
Maintainer: **samdark** Stability: **stable**
@property \Codeception\Lib\Connector\Yii2 $client
Actions
-------
### \_findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$els = $this->getModule('Yii2')->_findElements('.items');
$els = $this->getModule('Yii2')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('Yii2')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return array` of interactive elements
### \_getResponseContent
*hidden API method, expected to be used from Helper classes*
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
```
<?php
// in Helper class
public function seeResponseContains($text)
{
$this->assertStringContainsString($text, $this->getModule('Yii2')->_getResponseContent(), "response contains");
}
```
* `return string` @throws ModuleException
### \_loadPage
*hidden API method, expected to be used from Helper classes*
Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step.
```
<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
$this->getModule('Yii2')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
```
* `param string` $method
* `param string` $uri
* `param string` $content
### \_request
*hidden API method, expected to be used from Helper classes*
Send custom request to a backend using method, uri, parameters, etc. Use it in Helpers to create special request actions, like accessing API Returns a string with response body.
```
<?php
// in Helper class
public function createUserByApi($name) {
$userData = $this->getModule('Yii2')->_request('POST', '/api/v1/users', ['name' => $name]);
$user = json_decode($userData);
return $user->id;
}
```
Does not load the response into the module so you can’t interact with response page (click, fill forms). To load arbitrary page for interaction, use `_loadPage` method.
* `param string` $method
* `param string` $uri
* `param string` $content
* `return string` @throws ExternalUrlException @see `_loadPage`
### \_savePageSource
*hidden API method, expected to be used from Helper classes*
Saves page source of to a file
```
$this->getModule('Yii2')->_savePageSource(codecept_output_dir().'page.html');
```
* `param` $filename
### amHttpAuthenticated
Authenticates user for HTTP\_AUTH
* `param string` $username
* `param string` $password
### amLoggedInAs
Authenticates a user on a site without submitting a login form. Use it for fast pragmatic authorization in functional tests.
```
<?php
// User is found by id
$I->amLoggedInAs(1);
// User object is passed as parameter
$admin = \app\models\User::findByUsername('admin');
$I->amLoggedInAs($admin);
```
Requires the `user` component to be enabled and configured.
* `param` $user @throws ModuleException
### amOnPage
Opens the page for the given relative URI or route.
```
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
// opens customer view page for id 25
$I->amOnPage(['customer/view', 'id' => 25]);
```
* `param string|array` $page the URI or route in array format
### amOnRoute
Similar to `amOnPage` but accepts a route as first argument and params as second
```
$I->amOnRoute('site/view', ['page' => 'about']);
```
* `param string` $route A route
* `param array` $params Additional route parameters
### attachFile
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
```
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
```
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### click
Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
```
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### createAndSetCsrfCookie
Creates the CSRF Cookie.
* `param string` $val The value of the CSRF token
* `return string[]` Returns an array containing the name of the CSRF param and the masked CSRF token.
### deleteHeader
Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
```
* `param string` $name the name of the header to delete.
### dontSee
Checks that the current page doesn’t contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region.
```
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will ignore strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
```
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn’t a cookie with the given name. You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn’t equal the given string. Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
```
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn’t match the given regular expression.
```
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page. You can also specify expected attributes of this element.
```
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeEmailIsSent
Checks that no email was sent
* `[Part]` email
### dontSeeInCurrentUrl
Checks that the current URI doesn’t contain the given string.
```
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### dontSeeInField
Checks that an input field or textarea doesn’t contain the given value. For fuzzy locators, the field is matched by label text, CSS and XPath.
```
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
```
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn’t been assigned any one of many values, an array can be passed as the value:
```
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn’t contain a link with the given string. If the second parameter is given, only links with a matching “href” attribute will be checked.
```
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param string` $text
* `param string` $url optional
### dontSeeOptionIsSelected
Checks that the given option is not selected.
```
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### dontSeeRecord
Checks that a record does not exist in the database.
```
$I->dontSeeRecord('app\models\User', array('name' => 'davert'));
```
* `param` $model
* `param array` $attributes
* `[Part]` orm
### dontSeeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->dontSeeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### fillField
Fills a text field or textarea with the given string.
```
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], '[email protected]');
?>
```
* `param` $field
* `param` $value
### followRedirect
Follow pending redirect if there is one.
```
<?php
$I->followRedirect();
```
### getInternalDomains
Returns a list of regex patterns for recognized domain names
* `return array`
### grabAttributeFrom
Grabs the value of the given attribute value from the given element. Fails if element is not found.
```
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabComponent
Gets a component from the Yii container. Throws an exception if the component is not available
```
<?php
$mailer = $I->grabComponent('mailer');
```
* `param` $component @throws ModuleException @deprecated in your tests you can use \Yii::$app directly.
### grabCookie
Grabs a cookie value. You can set additional cookie params like `domain`, `path` in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try `$I->wait(0.1)`.
* `param` $cookie
* `param array` $params
### grabFixture
Gets a fixture by name. Returns a Fixture instance. If a fixture is an instance of `\yii\test\BaseActiveFixture` a second parameter can be used to return a specific model:
```
<?php
$I->haveFixtures(['users' => UserFixture::className()]);
$users = $I->grabFixture('users');
// get first user by key, if a fixture is an instance of ActiveFixture
$user = $I->grabFixture('users', 'user1');
```
* `param` $name @throws ModuleException if the fixture is not found
* `[Part]` fixtures
### grabFixtures
Returns all loaded fixtures. Array of fixture instances
* `[Part]` fixtures
* `return array`
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
```
<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param string` $uri optional
### grabLastSentEmail
Returns the last sent email:
```
<?php
$I->seeEmailIsSent();
$message = $I->grabLastSentEmail();
$I->assertEquals('admin@site,com', $message->getTo());
```
* `[Part]` email
### grabMultiple
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
```
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return string[]`
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return string` Current page source code.
### grabRecord
Retrieves a record from the database
```
$category = $I->grabRecord('app\models\User', array('name' => 'davert'));
```
* `param` $model
* `param array` $attributes
* `[Part]` orm
### grabSentEmails
Returns array of all sent email messages. Each message implements the `yii\mail\MessageInterface` interface. Useful to perform additional checks using the `Asserts` module:
```
<?php
$I->seeEmailIsSent();
$messages = $I->grabSentEmails();
$I->assertEquals('admin@site,com', $messages[0]->getTo());
```
* `[Part]` email
* `return array` @throws ModuleException
### grabTextFrom
Finds and returns the text contents of the given element. If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
```
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
* `param` $field
* `return array|mixed|null|string`
### haveFixtures
Creates and loads fixtures from a config. The signature is the same as for the `fixtures()` method of `yii\test\FixtureTrait`
```
<?php
$I->haveFixtures([
'posts' => PostsFixture::className(),
'user' => [
'class' => UserFixture::className(),
'dataFile' => '@tests/_data/models/user.php',
],
]);
```
Note: if you need to load fixtures before a test (probably before the cleanup transaction is started; `cleanup` option is `true` by default), you can specify the fixtures in the `_fixtures()` method of a test case
```
<?php
// inside Cest file or Codeception\TestCase\Unit
public function _fixtures(){
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => codecept_data_dir() . 'user.php'
]
];
}
```
instead of calling `haveFixtures` in Cest `_before`
* `param` $fixtures
* `[Part]` fixtures
### haveHttpHeader
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
```
To use special chars in Header Key use HTML Character Entities: Example: Header with underscore - ‘Client\_Id’ should be represented as - ‘Client\_Id’ or ‘Client\_Id’
```
<?php
$I->haveHttpHeader('Client_Id', 'Codeception');
```
* `param string` $name the name of the request header
* `param string` $value the value to set it to for subsequent requests
### haveRecord
Inserts a record into the database.
```
<?php
$user_id = $I->haveRecord('app\models\User', array('name' => 'Davert'));
?>
```
* `param` $model
* `param array` $attributes
* `[Part]` orm
### haveServerParameter
Sets SERVER parameter valid for all next requests.
```
$I->haveServerParameter('name', 'value');
```
* `param string` $name
* `param string` $value
### makeHtmlSnapshot
Use this method within an [interactive pause](../02-gettingstarted#Interactive-Pause) to save the HTML source code of the current page.
```
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
```
* `param null` $name
### moveBack
Moves back in history.
* `param int` $numberOfSteps (default value 1)
### resetCookie
Unsets cookie with the given name. You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.
```
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->see('strong')` will return true for strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
```
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set. You can set additional cookie params like `domain`, `path` as array passed in last argument.
```
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string. Unlike `seeInCurrentUrl`, this only matches the full URL.
```
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
```
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### seeElement
Checks that the given element exists on the page and is visible. You can also specify expected attributes of this element.
```
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
### seeEmailIsSent
Checks that an email is sent.
```
<?php
// check that at least 1 email was sent
$I->seeEmailIsSent();
// check that only 3 emails were sent
$I->seeEmailIsSent(3);
```
* `param int` $num @throws ModuleException
* `[Part]` email
### seeInCurrentUrl
Checks that current URI contains the given string.
```
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### seeInField
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value. Fields are matched by label text, the “name” attribute, CSS, or XPath.
```
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
```
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
```
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
```
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there’s a link with the specified text. Give a full URL as the second parameter to match links with that exact URL.
```
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param string` $text
* `param string` $url optional
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
```
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected int or int[]
### seeOptionIsSelected
Checks that the given option is selected.
```
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### seePageNotFound
Asserts that current page has 404 response status code.
### seeRecord
Checks that a record exists in the database.
```
$I->seeRecord('app\models\User', array('name' => 'davert'));
```
* `param` $model
* `param array` $attributes
* `[Part]` orm
### seeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->seeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### seeResponseCodeIsBetween
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
* `param int` $from
* `param int` $to
### seeResponseCodeIsClientError
Checks that the response code is 4xx
### seeResponseCodeIsRedirection
Checks that the response code 3xx
### seeResponseCodeIsServerError
Checks that the response code is 5xx
### seeResponseCodeIsSuccessful
Checks that the response code 2xx
### selectOption
Selects an option in a select tag or in radio button group.
```
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
```
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
```
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### sendAjaxGetRequest
Sends an ajax GET request with the passed parameters. See `sendAjaxPostRequest()`
* `param` $uri
* `param` $params
### sendAjaxPostRequest
Sends an ajax POST request with the passed parameters. The appropriate HTTP header is added automatically: `X-Requested-With: XMLHttpRequest` Example:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['task' => 'lorem ipsum']);
```
Some frameworks (e.g. Symfony) create field names in the form of an “array”: `<input type="text" name="form[task]">` In this case you need to pass the fields like this:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['form' => [
'task' => 'lorem ipsum',
'category' => 'miscellaneous',
]]);
```
* `param string` $uri
* `param array` $params
### sendAjaxRequest
Sends an ajax request, using the passed HTTP method. See `sendAjaxPostRequest()` Example:
```
<?php
$I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
```
* `param` $method
* `param` $uri
* `param array` $params
### setCookie
Sets a cookie and, if validation is enabled, signs it.
* `param string` $name The name of the cookie
* `param string` $value The value of the cookie
* `param array` $params Additional cookie params like `domain`, `path`, `expires` and `secure`.
### setMaxRedirects
Sets the maximum number of redirects that the Client can follow.
```
<?php
$I->setMaxRedirects(2);
```
* `param int` $maxRedirects
### setServerParameters
Sets SERVER parameters valid for all next requests. this will remove old ones.
```
$I->setServerParameters([]);
```
### startFollowingRedirects
Enables automatic redirects to be followed by the client.
```
<?php
$I->startFollowingRedirects();
```
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client.
```
<?php
$I->stopFollowingRedirects();
```
### submitForm
Submits the given form on the page, with the given form values. Pass the form field’s values as an array in the second parameter.
Although this function can be used as a short-hand version of `fillField()`, `selectOption()`, `click()` etc. it has some important differences:
* Only field *names* may be used, not CSS/XPath selectors nor field labels
* If a field is sent to this function that does *not* exist on the page, it will silently be added to the HTTP request. This is helpful for testing some types of forms, but be aware that you will *not* get an exception like you would if you called `fillField()` or `selectOption()` with a missing field.
Fields that are not provided will be filled by their values from the page, or from any previous calls to `fillField()`, `selectOption()` etc. You don’t need to click the ‘Submit’ button afterwards. This command itself triggers the request to form’s action.
You can optionally specify which button’s value to include in the request with the last parameter (as an alternative to explicitly setting its value in the second parameter), as button values are not otherwise included in the request.
Examples:
```
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample “Sign Up” form:
```
<form id="userForm">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Subscribe to our newsletter?
<input type="checkbox" name="user[newsletter]" value="1" checked="checked" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
],
'submitButton'
);
```
Note that “2” will be the submitted value for the “plan” field, as it is the selected option.
To uncheck the pre-checked checkbox “newsletter”, call `$I->uncheckOption(['name' => 'user[newsletter]']);` *before*, then submit the form as shown here (i.e. without the “newsletter” field in the `$params` array).
You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
]
);
```
This function works well when paired with `seeInFormFields()` for quickly testing CRUD interfaces and form validation logic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);
```
Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean `true`/`false` which will be replaced by the checkbox’s value in the DOM.
```
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false
],
'multiselect' => [
'first option value',
'second option value'
]
]);
```
Mixing string and boolean values for a checkbox’s value is not supported and may produce unexpected results.
Field names ending in `[]` must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:
```
<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```
<?php
// This way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
* `param` $selector
* `param` $params
* `param` $button
### switchToIframe
Switch to iframe or frame on the page.
Example:
```
<iframe name="another_frame" src="http://example.com">
```
```
<?php
# switch to iframe
$I->switchToIframe("another_frame");
```
* `param string` $name
### uncheckOption
Unticks a checkbox.
```
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
| programming_docs |
codeception Mezzio Mezzio
======
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-mezzio
```
Alternatively, you can enable `Mezzio` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module allows you to run tests inside Mezzio.
Uses `config/container.php` file by default.
Status
------
* Maintainer: **Naktibalda**
* Stability: **alpha**
Config
------
* `container` - (default: `config/container.php`) relative path to file which returns Container
* `recreateApplicationBetweenTests` - (default: false) whether to recreate the whole application before each test
* `recreateApplicationBetweenRequests` - (default: false) whether to recreate the whole application before each request
Public properties
-----------------
* application - instance of `\Mezzio\Application`
* container - instance of `\Interop\Container\ContainerInterface`
* client - BrowserKit client
Actions
-------
### \_findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$els = $this->getModule('Mezzio')->_findElements('.items');
$els = $this->getModule('Mezzio')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('Mezzio')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return array` of interactive elements
### \_getResponseContent
*hidden API method, expected to be used from Helper classes*
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
```
<?php
// in Helper class
public function seeResponseContains($text)
{
$this->assertStringContainsString($text, $this->getModule('Mezzio')->_getResponseContent(), "response contains");
}
```
* `return string` @throws ModuleException
### \_loadPage
*hidden API method, expected to be used from Helper classes*
Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step.
```
<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
$this->getModule('Mezzio')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
```
* `param string` $method
* `param string` $uri
* `param string` $content
### \_request
*hidden API method, expected to be used from Helper classes*
Send custom request to a backend using method, uri, parameters, etc. Use it in Helpers to create special request actions, like accessing API Returns a string with response body.
```
<?php
// in Helper class
public function createUserByApi($name) {
$userData = $this->getModule('Mezzio')->_request('POST', '/api/v1/users', ['name' => $name]);
$user = json_decode($userData);
return $user->id;
}
```
Does not load the response into the module so you can’t interact with response page (click, fill forms). To load arbitrary page for interaction, use `_loadPage` method.
* `param string` $method
* `param string` $uri
* `param string` $content
* `return string` @throws ExternalUrlException @see `_loadPage`
### \_savePageSource
*hidden API method, expected to be used from Helper classes*
Saves page source of to a file
```
$this->getModule('Mezzio')->_savePageSource(codecept_output_dir().'page.html');
```
* `param` $filename
### amHttpAuthenticated
Authenticates user for HTTP\_AUTH
* `param string` $username
* `param string` $password
### amOnPage
Opens the page for the given relative URI.
```
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
```
* `param string` $page
### attachFile
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
```
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
```
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### click
Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
```
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### deleteHeader
Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
```
* `param string` $name the name of the header to delete.
### dontSee
Checks that the current page doesn’t contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region.
```
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will ignore strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
```
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn’t a cookie with the given name. You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn’t equal the given string. Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
```
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn’t match the given regular expression.
```
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page. You can also specify expected attributes of this element.
```
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeInCurrentUrl
Checks that the current URI doesn’t contain the given string.
```
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### dontSeeInField
Checks that an input field or textarea doesn’t contain the given value. For fuzzy locators, the field is matched by label text, CSS and XPath.
```
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
```
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn’t been assigned any one of many values, an array can be passed as the value:
```
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn’t contain a link with the given string. If the second parameter is given, only links with a matching “href” attribute will be checked.
```
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param string` $text
* `param string` $url optional
### dontSeeOptionIsSelected
Checks that the given option is not selected.
```
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### dontSeeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->dontSeeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### fillField
Fills a text field or textarea with the given string.
```
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], '[email protected]');
?>
```
* `param` $field
* `param` $value
### followRedirect
Follow pending redirect if there is one.
```
<?php
$I->followRedirect();
```
### grabAttributeFrom
Grabs the value of the given attribute value from the given element. Fails if element is not found.
```
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabCookie
Grabs a cookie value. You can set additional cookie params like `domain`, `path` in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try `$I->wait(0.1)`.
* `param` $cookie
* `param array` $params
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
```
<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param string` $uri optional
### grabMultiple
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
```
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return string[]`
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return string` Current page source code.
### grabTextFrom
Finds and returns the text contents of the given element. If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
```
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
* `param` $field
* `return array|mixed|null|string`
### haveHttpHeader
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
```
To use special chars in Header Key use HTML Character Entities: Example: Header with underscore - ‘Client\_Id’ should be represented as - ‘Client\_Id’ or ‘Client\_Id’
```
<?php
$I->haveHttpHeader('Client_Id', 'Codeception');
```
* `param string` $name the name of the request header
* `param string` $value the value to set it to for subsequent requests
### haveServerParameter
Sets SERVER parameter valid for all next requests.
```
$I->haveServerParameter('name', 'value');
```
* `param string` $name
* `param string` $value
### makeHtmlSnapshot
Use this method within an [interactive pause](../02-gettingstarted#Interactive-Pause) to save the HTML source code of the current page.
```
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
```
* `param null` $name
### moveBack
Moves back in history.
* `param int` $numberOfSteps (default value 1)
### resetCookie
Unsets cookie with the given name. You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.
```
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->see('strong')` will return true for strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
```
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set. You can set additional cookie params like `domain`, `path` as array passed in last argument.
```
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string. Unlike `seeInCurrentUrl`, this only matches the full URL.
```
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
```
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### seeElement
Checks that the given element exists on the page and is visible. You can also specify expected attributes of this element.
```
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
### seeInCurrentUrl
Checks that current URI contains the given string.
```
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### seeInField
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value. Fields are matched by label text, the “name” attribute, CSS, or XPath.
```
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
```
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
```
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
```
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there’s a link with the specified text. Give a full URL as the second parameter to match links with that exact URL.
```
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param string` $text
* `param string` $url optional
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
```
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected int or int[]
### seeOptionIsSelected
Checks that the given option is selected.
```
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### seePageNotFound
Asserts that current page has 404 response status code.
### seeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->seeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### seeResponseCodeIsBetween
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
* `param int` $from
* `param int` $to
### seeResponseCodeIsClientError
Checks that the response code is 4xx
### seeResponseCodeIsRedirection
Checks that the response code 3xx
### seeResponseCodeIsServerError
Checks that the response code is 5xx
### seeResponseCodeIsSuccessful
Checks that the response code 2xx
### selectOption
Selects an option in a select tag or in radio button group.
```
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
```
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
```
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### sendAjaxGetRequest
Sends an ajax GET request with the passed parameters. See `sendAjaxPostRequest()`
* `param` $uri
* `param` $params
### sendAjaxPostRequest
Sends an ajax POST request with the passed parameters. The appropriate HTTP header is added automatically: `X-Requested-With: XMLHttpRequest` Example:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['task' => 'lorem ipsum']);
```
Some frameworks (e.g. Symfony) create field names in the form of an “array”: `<input type="text" name="form[task]">` In this case you need to pass the fields like this:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['form' => [
'task' => 'lorem ipsum',
'category' => 'miscellaneous',
]]);
```
* `param string` $uri
* `param array` $params
### sendAjaxRequest
Sends an ajax request, using the passed HTTP method. See `sendAjaxPostRequest()` Example:
```
<?php
$I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
```
* `param` $method
* `param` $uri
* `param array` $params
### setCookie
Sets a cookie with the given name and value. You can set additional cookie params like `domain`, `path`, `expires`, `secure` in array passed as last argument.
```
<?php
$I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
?>
```
* `param` $name
* `param` $val
* `param array` $params
### setMaxRedirects
Sets the maximum number of redirects that the Client can follow.
```
<?php
$I->setMaxRedirects(2);
```
* `param int` $maxRedirects
### setServerParameters
Sets SERVER parameters valid for all next requests. this will remove old ones.
```
$I->setServerParameters([]);
```
### startFollowingRedirects
Enables automatic redirects to be followed by the client.
```
<?php
$I->startFollowingRedirects();
```
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client.
```
<?php
$I->stopFollowingRedirects();
```
### submitForm
Submits the given form on the page, with the given form values. Pass the form field’s values as an array in the second parameter.
Although this function can be used as a short-hand version of `fillField()`, `selectOption()`, `click()` etc. it has some important differences:
* Only field *names* may be used, not CSS/XPath selectors nor field labels
* If a field is sent to this function that does *not* exist on the page, it will silently be added to the HTTP request. This is helpful for testing some types of forms, but be aware that you will *not* get an exception like you would if you called `fillField()` or `selectOption()` with a missing field.
Fields that are not provided will be filled by their values from the page, or from any previous calls to `fillField()`, `selectOption()` etc. You don’t need to click the ‘Submit’ button afterwards. This command itself triggers the request to form’s action.
You can optionally specify which button’s value to include in the request with the last parameter (as an alternative to explicitly setting its value in the second parameter), as button values are not otherwise included in the request.
Examples:
```
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample “Sign Up” form:
```
<form id="userForm">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Subscribe to our newsletter?
<input type="checkbox" name="user[newsletter]" value="1" checked="checked" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
],
'submitButton'
);
```
Note that “2” will be the submitted value for the “plan” field, as it is the selected option.
To uncheck the pre-checked checkbox “newsletter”, call `$I->uncheckOption(['name' => 'user[newsletter]']);` *before*, then submit the form as shown here (i.e. without the “newsletter” field in the `$params` array).
You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
]
);
```
This function works well when paired with `seeInFormFields()` for quickly testing CRUD interfaces and form validation logic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);
```
Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean `true`/`false` which will be replaced by the checkbox’s value in the DOM.
```
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false
],
'multiselect' => [
'first option value',
'second option value'
]
]);
```
Mixing string and boolean values for a checkbox’s value is not supported and may produce unexpected results.
Field names ending in `[]` must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:
```
<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```
<?php
// This way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
* `param` $selector
* `param` $params
* `param` $button
### switchToIframe
Switch to iframe or frame on the page.
Example:
```
<iframe name="another_frame" src="http://example.com">
```
```
<?php
# switch to iframe
$I->switchToIframe("another_frame");
```
* `param string` $name
### uncheckOption
Unticks a checkbox.
```
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
| programming_docs |
codeception Laravel Laravel
=======
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-laravel
```
Alternatively, you can enable `Laravel` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module allows you to run functional tests for Laravel 6.0+ It should **not** be used for acceptance tests. See the Acceptance tests section below for more details.
Demo project
------------
<https://github.com/Codeception/laravel-module-tests>
Config
------
* cleanup: `boolean`, default `true` - all database queries will be run in a transaction, which will be rolled back at the end of each test.
* run\_database\_migrations: `boolean`, default `false` - run database migrations before each test.
* database\_migrations\_path: `string`, default `null` - path to the database migrations, relative to the root of the application.
* run\_database\_seeder: `boolean`, default `false` - run database seeder before each test.
* database\_seeder\_class: `string`, default `` - database seeder class name.
* environment\_file: `string`, default `.env` - the environment file to load for the tests.
* bootstrap: `string`, default `bootstrap/app.php` - relative path to app.php config file.
* root: `string`, default `` - root path of the application.
* packages: `string`, default `workbench` - root path of application packages (if any).
* vendor\_dir: `string`, default `vendor` - optional relative path to vendor directory.
* disable\_exception\_handling: `boolean`, default `true` - disable Laravel exception handling.
* disable\_middleware: `boolean`, default `false` - disable all middleware.
* disable\_events: `boolean`, default `false` - disable events (does not disable model events).
* disable\_model\_events: `boolean`, default `false` - disable model events.
* url: `string`, default `` - the application URL.
### Example #1 (`functional.suite.yml`)
Enabling module:
```
yml
modules:
enabled:
- Laravel
```
### Example #2 (`functional.suite.yml`)
Enabling module with custom .env file
```
yml
modules:
enabled:
- Laravel:
environment_file: .env.testing
```
API
---
* app - `Illuminate\Foundation\Application`
* config - `array`
Parts
-----
* `ORM`: Only include the database methods of this module:
+ dontSeeRecord
+ grabNumRecords
+ grabRecord
+ have
+ haveMultiple
+ haveRecord
+ make
+ makeMultiple
+ seedDatabase
+ seeNumRecords
+ seeRecord
See [WebDriver module](webdriver#Loading-Parts-from-other-Modules) for general information on how to load parts of a framework module.
Acceptance tests
----------------
You should not use this module for acceptance tests. If you want to use Eloquent within your acceptance tests (paired with WebDriver) enable only ORM part of this module:
### Example (`acceptance.suite.yml`)
```
modules:
enabled:
- WebDriver:
browser: chrome
url: http://127.0.0.1:8000
- Laravel:
part: ORM
environment_file: .env.testing
```
Actions
-------
### \_findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$els = $this->getModule('Laravel')->_findElements('.items');
$els = $this->getModule('Laravel')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('Laravel')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return array` of interactive elements
### \_getResponseContent
*hidden API method, expected to be used from Helper classes*
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
```
<?php
// in Helper class
public function seeResponseContains($text)
{
$this->assertStringContainsString($text, $this->getModule('Laravel')->_getResponseContent(), "response contains");
}
```
* `return string` @throws ModuleException
### \_loadPage
*hidden API method, expected to be used from Helper classes*
Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step.
```
<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
$this->getModule('Laravel')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
```
* `param string` $method
* `param string` $uri
* `param string` $content
### \_request
*hidden API method, expected to be used from Helper classes*
Send custom request to a backend using method, uri, parameters, etc. Use it in Helpers to create special request actions, like accessing API Returns a string with response body.
```
<?php
// in Helper class
public function createUserByApi($name) {
$userData = $this->getModule('Laravel')->_request('POST', '/api/v1/users', ['name' => $name]);
$user = json_decode($userData);
return $user->id;
}
```
Does not load the response into the module so you can’t interact with response page (click, fill forms). To load arbitrary page for interaction, use `_loadPage` method.
* `param string` $method
* `param string` $uri
* `param string` $content
* `return string` @throws ExternalUrlException @see `_loadPage`
### \_savePageSource
*hidden API method, expected to be used from Helper classes*
Saves page source of to a file
```
$this->getModule('Laravel')->_savePageSource(codecept_output_dir().'page.html');
```
* `param` $filename
### amActingAs
Set the given user object to the current or specified Guard.
```
<?php
$I->amActingAs($user);
```
### amHttpAuthenticated
Authenticates user for HTTP\_AUTH
* `param string` $username
* `param string` $password
### amLoggedAs
Set the currently logged in user for the application. Unlike ‘amActingAs’, this method does update the session, fire the login events and remember the user as it assigns the corresponding Cookie.
```
<?php
// provide array of credentials
$I->amLoggedAs(['username' => '[email protected]', 'password' => 'password']);
// provide User object that implements the User interface
$I->amLoggedAs( new User );
// can be verified with $I->seeAuthentication();
```
* `param Authenticatable|array` $user
* `param string|null` $guardName
### amOnAction
Opens web page by action name
```
<?php
// Laravel 6 or 7:
$I->amOnAction('PostsController@index');
// Laravel 8+:
$I->amOnAction(PostsController::class . '@index');
```
* `param string` $action
* `param mixed` $parameters
### amOnPage
Opens the page for the given relative URI.
```
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
```
* `param string` $page
### amOnRoute
Opens web page using route name and parameters.
```
<?php
$I->amOnRoute('posts.create');
```
* `param string` $routeName
* `param mixed` $params
### assertAuthenticatedAs
Assert that the user is authenticated as the given user.
```
<?php
$I->assertAuthenticatedAs($user);
```
### assertCredentials
Assert that the given credentials are valid.
```
<?php
$I->assertCredentials([
'email' => '[email protected]',
'password' => '123456'
]);
```
### assertInvalidCredentials
Assert that the given credentials are invalid.
```
<?php
$I->assertInvalidCredentials([
'email' => '[email protected]',
'password' => 'wrong_password'
]);
```
### attachFile
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
```
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### callArtisan
Call an Artisan command.
```
<?php
$I->callArtisan('command:name');
$I->callArtisan('command:name', ['parameter' => 'value']);
```
Use 3rd parameter to pass in custom `OutputInterface`
* `return string|void`
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
```
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### clearApplicationHandlers
Clear the registered application handlers.
```
<?php
$I->clearApplicationHandlers();
```
### click
Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
```
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### deleteHeader
Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
```
* `param string` $name the name of the header to delete.
### disableEvents
Disable events for the next requests. This method does not disable model events. To disable model events you have to use the disableModelEvents() method.
```
<?php
$I->disableEvents();
```
### disableExceptionHandling
Disable Laravel exception handling.
```
<?php
$I->disableExceptionHandling();
```
### disableMiddleware
Disable middleware for the next requests.
```
<?php
$I->disableMiddleware();
```
* `param string|array|null` $middleware
### disableModelEvents
Disable model events for the next requests.
```
<?php
$I->disableModelEvents();
```
### dontSee
Checks that the current page doesn’t contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region.
```
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will ignore strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### dontSeeAuthentication
Check that user is not authenticated.
```
<?php
$I->dontSeeAuthentication();
```
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
```
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn’t a cookie with the given name. You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn’t equal the given string. Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
```
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn’t match the given regular expression.
```
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page. You can also specify expected attributes of this element.
```
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeEventTriggered
Make sure events did not fire during the test.
```
<?php
$I->dontSeeEventTriggered('App\MyEvent');
$I->dontSeeEventTriggered(new App\Events\MyEvent());
$I->dontSeeEventTriggered(['App\MyEvent', 'App\MyOtherEvent']);
```
* `param string|object|string[]` $expected
### dontSeeFormErrors
Assert that there are no form errors bound to the View.
```
<?php
$I->dontSeeFormErrors();
```
### dontSeeInCurrentUrl
Checks that the current URI doesn’t contain the given string.
```
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### dontSeeInField
Checks that an input field or textarea doesn’t contain the given value. For fuzzy locators, the field is matched by label text, CSS and XPath.
```
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
```
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn’t been assigned any one of many values, an array can be passed as the value:
```
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInSession
Assert that a session attribute does not exist, or is not equal to the passed value.
```
<?php
$I->dontSeeInSession('attribute');
$I->dontSeeInSession('attribute', 'value');
```
* `param string|array` $key
* `param mixed|null` $value
### dontSeeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn’t contain a link with the given string. If the second parameter is given, only links with a matching “href” attribute will be checked.
```
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param string` $text
* `param string` $url optional
### dontSeeOptionIsSelected
Checks that the given option is not selected.
```
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### dontSeeRecord
Checks that record does not exist in database. You can pass the name of a database table or the class name of an Eloquent model as the first argument.
```
<?php
$I->dontSeeRecord($user);
$I->dontSeeRecord('users', ['name' => 'Davert']);
$I->dontSeeRecord('App\Models\User', ['name' => 'Davert']);
```
* `param string|class-string|object` $table
* `param array` $attributes
* `[Part]` orm
### dontSeeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->dontSeeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### dontSeeSessionHasValues
Assert that the session does not have a particular list of values.
```
<?php
$I->dontSeeSessionHasValues(['key1', 'key2']);
$I->dontSeeSessionHasValues(['key1' => 'value1', 'key2' => 'value2']);
```
### enableExceptionHandling
Enable Laravel exception handling.
```
<?php
$I->enableExceptionHandling();
```
### enableMiddleware
Enable the given middleware for the next requests.
```
<?php
$I->enableMiddleware();
```
* `param string|array|null` $middleware
### fillField
Fills a text field or textarea with the given string.
```
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], '[email protected]');
?>
```
* `param` $field
* `param` $value
### flushSession
Flush all of the current session data.
```
<?php
$I->flushSession();
```
### followRedirect
Follow pending redirect if there is one.
```
<?php
$I->followRedirect();
```
### getApplication
Provides access the Laravel application object.
```
<?php
$app = $I->getApplication();
```
### grabAttributeFrom
Grabs the value of the given attribute value from the given element. Fails if element is not found.
```
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabCookie
Grabs a cookie value. You can set additional cookie params like `domain`, `path` in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try `$I->wait(0.1)`.
* `param` $cookie
* `param array` $params
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
```
<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param string` $uri optional
### grabMultiple
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
```
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return string[]`
### grabNumRecords
Retrieves number of records from database You can pass the name of a database table or the class name of an Eloquent model as the first argument.
```
<?php
$I->grabNumRecords('users', ['name' => 'Davert']);
$I->grabNumRecords('App\Models\User', ['name' => 'Davert']);
```
* `[Part]` orm
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return string` Current page source code.
### grabRecord
Retrieves record from database If you pass the name of a database table as the first argument, this method returns an array. You can also pass the class name of an Eloquent model, in that case this method returns an Eloquent model.
```
<?php
$record = $I->grabRecord('users', ['name' => 'Davert']); // returns array
$record = $I->grabRecord('App\Models\User', ['name' => 'Davert']); // returns Eloquent model
```
* `param string` $table
* `param array` $attributes
* `return array|EloquentModel`
* `[Part]` orm
### grabService
Return an instance of a class from the Laravel service container. (https://laravel.com/docs/7.x/container)
```
<?php
// In Laravel
App::bind('foo', function($app) {
return new FooBar;
});
// Then in test
$service = $I->grabService('foo');
// Will return an instance of FooBar, also works for singletons.
```
### grabTextFrom
Finds and returns the text contents of the given element. If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
```
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
* `param` $field
* `return array|mixed|null|string`
### have
Use Laravel model factory to create a model.
```
<?php
$I->have('App\Models\User');
$I->have('App\Models\User', ['name' => 'John Doe']);
$I->have('App\Models\User', [], 'admin');
```
@see https://laravel.com/docs/7.x/database-testing#using-factories
* `[Part]` orm
### haveApplicationHandler
Register a handler than can be used to modify the Laravel application object after it is initialized. The Laravel application object will be passed as an argument to the handler.
```
<?php
$I->haveApplicationHandler(function($app) {
$app->make('config')->set(['test_value' => '10']);
});
```
### haveBinding
Add a binding to the Laravel service container. (https://laravel.com/docs/7.x/container)
```
<?php
$I->haveBinding('My\Interface', 'My\Implementation');
```
* `param string` $abstract
* `param Closure|string|null` $concrete
* `param bool` $shared
### haveContextualBinding
Add a contextual binding to the Laravel service container. (https://laravel.com/docs/7.x/container)
```
<?php
$I->haveContextualBinding('My\Class', '$variable', 'value');
// This is similar to the following in your Laravel application
$app->when('My\Class')
->needs('$variable')
->give('value');
```
* `param string` $concrete
* `param string` $abstract
* `param Closure|string` $implementation
### haveHttpHeader
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
```
To use special chars in Header Key use HTML Character Entities: Example: Header with underscore - ‘Client\_Id’ should be represented as - ‘Client\_Id’ or ‘Client\_Id’
```
<?php
$I->haveHttpHeader('Client_Id', 'Codeception');
```
* `param string` $name the name of the request header
* `param string` $value the value to set it to for subsequent requests
### haveInSession
Set the session to the given array.
```
<?php
$I->haveInSession(['myKey' => 'MyValue']);
```
### haveInstance
Add an instance binding to the Laravel service container. (https://laravel.com/docs/7.x/container)
```
<?php
$I->haveInstance('App\MyClass', new App\MyClass());
```
### haveMultiple
Use Laravel model factory to create multiple models.
```
<?php
$I->haveMultiple('App\Models\User', 10);
$I->haveMultiple('App\Models\User', 10, ['name' => 'John Doe']);
$I->haveMultiple('App\Models\User', 10, [], 'admin');
```
@see https://laravel.com/docs/7.x/database-testing#using-factories
* `return EloquentModel|EloquentCollection`
* `[Part]` orm
### haveRecord
Inserts record into the database. If you pass the name of a database table as the first argument, this method returns an integer ID. You can also pass the class name of an Eloquent model, in that case this method returns an Eloquent model.
```
<?php
$user_id = $I->haveRecord('users', ['name' => 'Davert']); // returns integer
$user = $I->haveRecord('App\Models\User', ['name' => 'Davert']); // returns Eloquent model
```
* `param string` $table
* `param array` $attributes
* `return EloquentModel|int` @throws RuntimeException
* `[Part]` orm
### haveServerParameter
Sets SERVER parameter valid for all next requests.
```
$I->haveServerParameter('name', 'value');
```
* `param string` $name
* `param string` $value
### haveSingleton
Add a singleton binding to the Laravel service container. (https://laravel.com/docs/7.x/container)
```
<?php
$I->haveSingleton('App\MyInterface', 'App\MySingleton');
```
* `param string` $abstract
* `param Closure|string|null` $concrete
### logout
Logout user.
```
<?php
$I->logout();
```
### make
Use Laravel model factory to make a model instance.
```
<?php
$I->make('App\Models\User');
$I->make('App\Models\User', ['name' => 'John Doe']);
$I->make('App\Models\User', [], 'admin');
```
@see https://laravel.com/docs/7.x/database-testing#using-factories
* `return EloquentCollection|EloquentModel`
* `[Part]` orm
### makeHtmlSnapshot
Use this method within an [interactive pause](../02-gettingstarted#Interactive-Pause) to save the HTML source code of the current page.
```
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
```
* `param null` $name
### makeMultiple
Use Laravel model factory to make multiple model instances.
```
<?php
$I->makeMultiple('App\Models\User', 10);
$I->makeMultiple('App\Models\User', 10, ['name' => 'John Doe']);
$I->makeMultiple('App\Models\User', 10, [], 'admin');
```
@see https://laravel.com/docs/7.x/database-testing#using-factories
* `return EloquentCollection|EloquentModel`
* `[Part]` orm
### moveBack
Moves back in history.
* `param int` $numberOfSteps (default value 1)
### resetCookie
Unsets cookie with the given name. You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.
```
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->see('strong')` will return true for strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### seeAuthentication
Checks that a user is authenticated.
```
<?php
$I->seeAuthentication();
```
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
```
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set. You can set additional cookie params like `domain`, `path` as array passed in last argument.
```
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentActionIs
Checks that current url matches action
```
<?php
// Laravel 6 or 7:
$I->seeCurrentActionIs('PostsController@index');
// Laravel 8+:
$I->seeCurrentActionIs(PostsController::class . '@index');
```
### seeCurrentRouteIs
Checks that current url matches route
```
<?php
$I->seeCurrentRouteIs('posts.index');
```
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string. Unlike `seeInCurrentUrl`, this only matches the full URL.
```
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
```
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### seeElement
Checks that the given element exists on the page and is visible. You can also specify expected attributes of this element.
```
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
### seeEventTriggered
Make sure events fired during the test.
```
<?php
$I->seeEventTriggered('App\MyEvent');
$I->seeEventTriggered(new App\Events\MyEvent());
$I->seeEventTriggered(['App\MyEvent', 'App\MyOtherEvent']);
```
* `param string|object|string[]` $expected
### seeFormErrorMessage
Assert that a specific form error message is set in the view.
If you want to assert that there is a form error message for a specific key but don’t care about the actual error message you can omit `$expectedErrorMessage`.
If you do pass `$expectedErrorMessage`, this method checks if the actual error message for a key contains `$expectedErrorMessage`.
```
<?php
$I->seeFormErrorMessage('username');
$I->seeFormErrorMessage('username', 'Invalid Username');
```
### seeFormErrorMessages
Verifies that multiple fields on a form have errors.
This method will validate that the expected error message is contained in the actual error message, that is, you can specify either the entire error message or just a part of it:
```
<?php
$I->seeFormErrorMessages([
'address' => 'The address is too long',
'telephone' => 'too short' // the full error message is 'The telephone is too short'
]);
```
If you don’t want to specify the error message for some fields, you can pass `null` as value instead of the message string. If that is the case, it will be validated that that field has at least one error of any type:
```
<?php
$I->seeFormErrorMessages([
'telephone' => 'too short',
'address' => null
]);
```
### seeFormHasErrors
Assert that form errors are bound to the View.
```
<?php
$I->seeFormHasErrors();
```
### seeInCurrentUrl
Checks that current URI contains the given string.
```
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### seeInField
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value. Fields are matched by label text, the “name” attribute, CSS, or XPath.
```
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
```
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
```
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInSession
Assert that a session variable exists.
```
<?php
$I->seeInSession('key');
$I->seeInSession('key', 'value');
```
* `param string|array` $key
* `param mixed|null` $value
### seeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
```
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there’s a link with the specified text. Give a full URL as the second parameter to match links with that exact URL.
```
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param string` $text
* `param string` $url optional
### seeNumRecords
Checks that number of given records were found in database. You can pass the name of a database table or the class name of an Eloquent model as the first argument.
```
<?php
$I->seeNumRecords(1, 'users', ['name' => 'Davert']);
$I->seeNumRecords(1, 'App\Models\User', ['name' => 'Davert']);
```
* `[Part]` orm
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
```
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected int or int[]
### seeOptionIsSelected
Checks that the given option is selected.
```
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### seePageNotFound
Asserts that current page has 404 response status code.
### seeRecord
Checks that record exists in database. You can pass the name of a database table or the class name of an Eloquent model as the first argument.
```
<?php
$I->seeRecord($user);
$I->seeRecord('users', ['name' => 'Davert']);
$I->seeRecord('App\Models\User', ['name' => 'Davert']);
```
* `param string|class-string|object` $table
* `param array` $attributes
* `[Part]` orm
### seeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->seeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### seeResponseCodeIsBetween
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
* `param int` $from
* `param int` $to
### seeResponseCodeIsClientError
Checks that the response code is 4xx
### seeResponseCodeIsRedirection
Checks that the response code 3xx
### seeResponseCodeIsServerError
Checks that the response code is 5xx
### seeResponseCodeIsSuccessful
Checks that the response code 2xx
### seeSessionHasValues
Assert that the session has a given list of values.
```
<?php
$I->seeSessionHasValues(['key1', 'key2']);
$I->seeSessionHasValues(['key1' => 'value1', 'key2' => 'value2']);
```
### seedDatabase
Seed a given database connection.
* `param class-string|class-string[]` $seeders
### selectOption
Selects an option in a select tag or in radio button group.
```
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
```
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
```
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### sendAjaxGetRequest
Sends an ajax GET request with the passed parameters. See `sendAjaxPostRequest()`
* `param` $uri
* `param` $params
### sendAjaxPostRequest
Sends an ajax POST request with the passed parameters. The appropriate HTTP header is added automatically: `X-Requested-With: XMLHttpRequest` Example:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['task' => 'lorem ipsum']);
```
Some frameworks (e.g. Symfony) create field names in the form of an “array”: `<input type="text" name="form[task]">` In this case you need to pass the fields like this:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['form' => [
'task' => 'lorem ipsum',
'category' => 'miscellaneous',
]]);
```
* `param string` $uri
* `param array` $params
### sendAjaxRequest
Sends an ajax request, using the passed HTTP method. See `sendAjaxPostRequest()` Example:
```
<?php
$I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
```
* `param` $method
* `param` $uri
* `param array` $params
### setApplication
**not documented**
### setCookie
Sets a cookie with the given name and value. You can set additional cookie params like `domain`, `path`, `expires`, `secure` in array passed as last argument.
```
<?php
$I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
?>
```
* `param` $name
* `param` $val
* `param array` $params
### setMaxRedirects
Sets the maximum number of redirects that the Client can follow.
```
<?php
$I->setMaxRedirects(2);
```
* `param int` $maxRedirects
### setServerParameters
Sets SERVER parameters valid for all next requests. this will remove old ones.
```
$I->setServerParameters([]);
```
### startFollowingRedirects
Enables automatic redirects to be followed by the client.
```
<?php
$I->startFollowingRedirects();
```
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client.
```
<?php
$I->stopFollowingRedirects();
```
### submitForm
Submits the given form on the page, with the given form values. Pass the form field’s values as an array in the second parameter.
Although this function can be used as a short-hand version of `fillField()`, `selectOption()`, `click()` etc. it has some important differences:
* Only field *names* may be used, not CSS/XPath selectors nor field labels
* If a field is sent to this function that does *not* exist on the page, it will silently be added to the HTTP request. This is helpful for testing some types of forms, but be aware that you will *not* get an exception like you would if you called `fillField()` or `selectOption()` with a missing field.
Fields that are not provided will be filled by their values from the page, or from any previous calls to `fillField()`, `selectOption()` etc. You don’t need to click the ‘Submit’ button afterwards. This command itself triggers the request to form’s action.
You can optionally specify which button’s value to include in the request with the last parameter (as an alternative to explicitly setting its value in the second parameter), as button values are not otherwise included in the request.
Examples:
```
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample “Sign Up” form:
```
<form id="userForm">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Subscribe to our newsletter?
<input type="checkbox" name="user[newsletter]" value="1" checked="checked" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
],
'submitButton'
);
```
Note that “2” will be the submitted value for the “plan” field, as it is the selected option.
To uncheck the pre-checked checkbox “newsletter”, call `$I->uncheckOption(['name' => 'user[newsletter]']);` *before*, then submit the form as shown here (i.e. without the “newsletter” field in the `$params` array).
You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
]
);
```
This function works well when paired with `seeInFormFields()` for quickly testing CRUD interfaces and form validation logic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);
```
Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean `true`/`false` which will be replaced by the checkbox’s value in the DOM.
```
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false
],
'multiselect' => [
'first option value',
'second option value'
]
]);
```
Mixing string and boolean values for a checkbox’s value is not supported and may produce unexpected results.
Field names ending in `[]` must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:
```
<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```
<?php
// This way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
* `param` $selector
* `param` $params
* `param` $button
### switchToIframe
Switch to iframe or frame on the page.
Example:
```
<iframe name="another_frame" src="http://example.com">
```
```
<?php
# switch to iframe
$I->switchToIframe("another_frame");
```
* `param string` $name
### uncheckOption
Unticks a checkbox.
```
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
| programming_docs |
codeception DataFactory DataFactory
===========
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-datafactory
```
Alternatively, you can enable `DataFactory` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
DataFactory allows you to easily generate and create test data using [**FactoryMuffin**](https://github.com/thephpleague/factory-muffin). DataFactory uses an ORM of your application to define, save and cleanup data. Thus, should be used with ORM or Framework modules.
This module requires packages installed:
```
{
"league/factory-muffin": "^3.0",
}
```
Generation rules can be defined in a factories file. You will need to create `factories.php` (it is recommended to store it in `_support` dir) Follow [FactoryMuffin documentation](https://github.com/thephpleague/factory-muffin) to set valid rules. Random data provided by [Faker](https://github.com/fzaninotto/Faker) library.
```
<?php
use League\FactoryMuffin\Faker\Facade as Faker;
$fm->define(User::class)->setDefinitions([
'name' => Faker::name(),
// generate email
'email' => Faker::email(),
'body' => Faker::text(),
// generate a profile and return its Id
'profile_id' => 'factory|Profile'
]);
```
Configure this module to load factory definitions from a directory. You should also specify a module with an ORM as a dependency.
```
modules:
enabled:
- Yii2:
configFile: path/to/config.php
- DataFactory:
factories: tests/_support/factories
depends: Yii2
```
(you can also use Laravel5 and Phalcon).
In this example factories are loaded from `tests/_support/factories` directory. Please note that this directory is relative from the codeception.yml file (so for Yii2 it would be codeception/\_support/factories). You should create this directory manually and create PHP files in it with factories definitions following [official documentation](https://github.com/thephpleague/factory-muffin#usage).
In cases you want to use data from database inside your factory definitions you can define them in Helper. For instance, if you use Doctrine, this allows you to access `EntityManager` inside a definition.
To proceed you should create Factories helper via `generate:helper` command and enable it:
```
modules:
enabled:
- DataFactory:
depends: Doctrine2
- \Helper\Factories
```
In this case you can define factories from a Helper class with `_define` method.
```
<?php
public function _beforeSuite()
{
$factory = $this->getModule('DataFactory');
// let us get EntityManager from Doctrine
$em = $this->getModule('Doctrine2')->_getEntityManager();
$factory->_define(User::class, [
// generate random user name
// use League\FactoryMuffin\Faker\Facade as Faker;
'name' => Faker::name(),
// get real company from database
'company' => $em->getRepository(Company::class)->find(),
// let's generate a profile for each created user
// receive an entity and set it via `setProfile` method
// UserProfile factory should be defined as well
'profile' => 'entity|'.UserProfile::class
]);
}
```
Factory Definitions are described in official [Factory Muffin Documentation](https://github.com/thephpleague/factory-muffin)
### Related Models Generators
If your module relies on other model you can generate them both. To create a related module you can use either `factory` or `entity` prefix, depending on ORM you use.
In case your ORM expects an Id of a related record (Eloquent) to be set use `factory` prefix:
```
'user_id' => 'factory|User'
```
In case your ORM expects a related record itself (Doctrine) then you should use `entity` prefix:
```
'user' => 'entity|User'
```
### Custom store
You can define a custom store for Factory Muffin using `customStore` parameter. It can be a simple class or a factory with `create` method. The instantiated object must implement `\League\FactoryMuffin\Stores\StoreInterface`.
Store factory example:
```
modules:
enabled:
- DataFactory:
customStore: \common\tests\store\MyCustomStoreFactory
```
```
use League\FactoryMuffin\Stores\StoreInterface;
class MyCustomStoreFactory
{
public function create(): StoreInterface
{
return CustomStore();
}
}
class CustomStore implements StoreInterface
{
// ...
}
```
Actions
-------
### have
Generates and saves a record,.
```
$I->have('User'); // creates user
$I->have('User', ['is_active' => true]); // creates active user
```
Returns an instance of created user.
* `param string` $name
* `param array` $extraAttrs
* `return object`
### haveMultiple
Generates and saves a record multiple times.
```
$I->haveMultiple('User', 10); // create 10 users
$I->haveMultiple('User', 10, ['is_active' => true]); // create 10 active users
```
* `param string` $name
* `param int` $times
* `param array` $extraAttrs
* `return \object[]`
### make
Generates a record instance.
This does not save it in the database. Use `have` for that.
```
$user = $I->make('User'); // return User instance
$activeUser = $I->make('User', ['is_active' => true]); // return active user instance
```
Returns an instance of created user without creating a record in database.
* `param string` $name
* `param array` $extraAttrs
* `return object`
### onReconfigure
@throws ModuleException
codeception Db Db
==
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-db
```
Alternatively, you can enable `Db` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Access a database.
The most important function of this module is to clean a database before each test. This module also provides actions to perform checks in a database, e.g. [seeInDatabase()](db#seeInDatabase)
In order to have your database populated with data you need a raw SQL dump. Simply put the dump in the `tests/_data` directory (by default) and specify the path in the config. The next time after the database is cleared, all your data will be restored from the dump. Don’t forget to include `CREATE TABLE` statements in the dump.
Supported and tested databases are:
* MySQL
* SQLite (i.e. just one file)
* PostgreSQL
Also available:
* MS SQL
* Oracle
Connection is done by database Drivers, which are stored in the `Codeception\Lib\Driver` namespace. [Check out the drivers](https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Lib/Driver) if you run into problems loading dumps and cleaning databases.
Config
------
* dsn *required* - PDO DSN
* user *required* - username to access database
* password *required* - password
* dump - path to database dump
* populate: false - whether the the dump should be loaded before the test suite is started
* cleanup: false - whether the dump should be reloaded before each test
* reconnect: false - whether the module should reconnect to the database before each test
* waitlock: 0 - wait lock (in seconds) that the database session should use for DDL statements
* ssl\_key - path to the SSL key (MySQL specific, @see http://php.net/manual/de/ref.pdo-mysql.php#pdo.constants.mysql-attr-key)
* ssl\_cert - path to the SSL certificate (MySQL specific, @see http://php.net/manual/de/ref.pdo-mysql.php#pdo.constants.mysql-attr-ssl-cert)
* ssl\_ca - path to the SSL certificate authority (MySQL specific, @see http://php.net/manual/de/ref.pdo-mysql.php#pdo.constants.mysql-attr-ssl-ca)
* ssl\_verify\_server\_cert - disables certificate CN verification (MySQL specific, @see http://php.net/manual/de/ref.pdo-mysql.php)
* ssl\_cipher - list of one or more permissible ciphers to use for SSL encryption (MySQL specific, @see http://php.net/manual/de/ref.pdo-mysql.php#pdo.constants.mysql-attr-cipher)
* databases - include more database configs and switch between them in tests.
* initial\_queries - list of queries to be executed right after connection to the database has been initiated, i.e. creating the database if it does not exist or preparing the database collation
Example
-------
`modules:
enabled:
- Db:
dsn: 'mysql:host=localhost;dbname=testdb'
user: 'root'
password: ''
dump: 'tests/_data/dump.sql'
populate: true
cleanup: true
reconnect: true
waitlock: 10
ssl_key: '/path/to/client-key.pem'
ssl_cert: '/path/to/client-cert.pem'
ssl_ca: '/path/to/ca-cert.pem'
ssl_verify_server_cert: false
ssl_cipher: 'AES256-SHA'
initial_queries:
- 'CREATE DATABASE IF NOT EXISTS temp_db;'
- 'USE temp_db;'
- 'SET NAMES utf8;'` Example with multi-dumps
------------------------
`modules:
enabled:
- Db:
dsn: 'mysql:host=localhost;dbname=testdb'
user: 'root'
password: ''
dump:
- 'tests/_data/dump.sql'
- 'tests/_data/dump-2.sql'` Example with multi-databases
----------------------------
`modules:
enabled:
- Db:
dsn: 'mysql:host=localhost;dbname=testdb'
user: 'root'
password: ''
databases:
db2:
dsn: 'mysql:host=localhost;dbname=testdb2'
user: 'userdb2'
password: ''` Example with Sqlite
-------------------
`modules:
enabled:
- Db:
dsn: 'sqlite:relative/path/to/sqlite-database.db'
user: ''
password: ''` SQL data dump
-------------
There are two ways of loading the dump into your database:
### Populator
The recommended approach is to configure a `populator`, an external command to load a dump. Command parameters like host, username, password, database can be obtained from the config and inserted into placeholders:
For MySQL:
```
modules:
enabled:
- Db:
dsn: 'mysql:host=localhost;dbname=testdb'
user: 'root'
password: ''
dump: 'tests/_data/dump.sql'
populate: true # run populator before all tests
cleanup: true # run populator before each test
populator: 'mysql -u $user -h $host $dbname < $dump'
```
For PostgreSQL (using pg\_restore)
```
modules:
enabled:
- Db:
dsn: 'pgsql:host=localhost;dbname=testdb'
user: 'root'
password: ''
dump: 'tests/_data/db_backup.dump'
populate: true # run populator before all tests
cleanup: true # run populator before each test
populator: 'pg_restore -u $user -h $host -D $dbname < $dump'
```
Variable names are being taken from config and DSN which has a `keyword=value` format, so you should expect to have a variable named as the keyword with the full value inside it.
PDO dsn elements for the supported drivers:
* MySQL: [PDO\_MYSQL DSN](https://secure.php.net/manual/en/ref.pdo-mysql.connection.php)
* SQLite: [PDO\_SQLITE DSN](https://secure.php.net/manual/en/ref.pdo-sqlite.connection.php) - use *relative* path from the project root
* PostgreSQL: [PDO\_PGSQL DSN](https://secure.php.net/manual/en/ref.pdo-pgsql.connection.php)
* MSSQL: [PDO\_SQLSRV DSN](https://secure.php.net/manual/en/ref.pdo-sqlsrv.connection.php)
* Oracle: [PDO\_OCI DSN](https://secure.php.net/manual/en/ref.pdo-oci.connection.php)
### Dump
Db module by itself can load SQL dump without external tools by using current database connection. This approach is system-independent, however, it is slower than using a populator and may have parsing issues (see below).
Provide a path to SQL file in `dump` config option:
```
modules:
enabled:
- Db:
dsn: 'mysql:host=localhost;dbname=testdb'
user: 'root'
password: ''
populate: true # load dump before all tests
cleanup: true # load dump for each test
dump: 'tests/_data/dump.sql'
```
To parse SQL Db file, it should follow this specification:
* Comments are permitted.
* The `dump.sql` may contain multiline statements.
* The delimiter, a semi-colon in this case, must be on the same line as the last statement:
```
-- Add a few contacts to the table.
REPLACE INTO `Contacts` (`created`, `modified`, `status`, `contact`, `first`, `last`) VALUES
(NOW(), NOW(), 1, 'Bob Ross', 'Bob', 'Ross'),
(NOW(), NOW(), 1, 'Fred Flintstone', 'Fred', 'Flintstone');
-- Remove existing orders for testing.
DELETE FROM `Order`;
```
Query generation
----------------
`seeInDatabase`, `dontSeeInDatabase`, `seeNumRecords`, `grabFromDatabase` and `grabNumRecords` methods accept arrays as criteria. WHERE condition is generated using item key as a field name and item value as a field value.
Example:
```
<?php
$I->seeInDatabase('users', ['name' => 'Davert', 'email' => '[email protected]']);
```
Will generate:
```
SELECT COUNT(*) FROM `users` WHERE `name` = 'Davert' AND `email` = '[email protected]'
```
Since version 2.1.9 it’s possible to use LIKE in a condition, as shown here:
```
<?php
$I->seeInDatabase('users', ['name' => 'Davert', 'email like' => 'davert%']);
```
Will generate:
```
SELECT COUNT(*) FROM `users` WHERE `name` = 'Davert' AND `email` LIKE 'davert%'
```
Null comparisons are also available, as shown here:
```
<?php
$I->seeInDatabase('users', ['name' => null, 'email !=' => null]);
```
Will generate:
```
SELECT COUNT(*) FROM `users` WHERE `name` IS NULL AND `email` IS NOT NULL
```
Public Properties
-----------------
* dbh - contains the PDO connection
* driver - contains the Connection Driver
Actions
-------
### amConnectedToDatabase
Make sure you are connected to the right database.
```
<?php
$I->seeNumRecords(2, 'users'); //executed on default database
$I->amConnectedToDatabase('db_books');
$I->seeNumRecords(30, 'books'); //executed on db_books database
//All the next queries will be on db_books
```
* `param` $databaseKey @throws ModuleConfigException
### dontSeeInDatabase
Effect is opposite to ->seeInDatabase
Asserts that there is no record with the given column values in a database. Provide table name and column values.
```
<?php
$I->dontSeeInDatabase('users', ['name' => 'Davert', 'email' => '[email protected]']);
```
Fails if such user was found.
Comparison expressions can be used as well:
```
<?php
$I->dontSeeInDatabase('posts', ['num_comments >=' => '0']);
$I->dontSeeInDatabase('users', ['email like' => 'miles%']);
```
Supported operators: `<`, `>`, `>=`, `<=`, `!=`, `like`.
* `param string` $table
* `param array` $criteria
### grabColumnFromDatabase
Fetches all values from the column in database. Provide table name, desired column and criteria.
```
<?php
$mails = $I->grabColumnFromDatabase('users', 'email', array('name' => 'RebOOter'));
```
* `param string` $table
* `param string` $column
* `param array` $criteria
* `return array`
### grabFromDatabase
Fetches a single column value from a database. Provide table name, desired column and criteria.
```
<?php
$mail = $I->grabFromDatabase('users', 'email', array('name' => 'Davert'));
```
Comparison expressions can be used as well:
```
<?php
$post = $I->grabFromDatabase('posts', ['num_comments >=' => 100]);
$user = $I->grabFromDatabase('users', ['email like' => 'miles%']);
```
Supported operators: `<`, `>`, `>=`, `<=`, `!=`, `like`.
* `param string` $table
* `param string` $column
* `param array` $criteria
* `return mixed` Returns a single column value or false
### grabNumRecords
Returns the number of rows in a database
* `param string` $table Table name
* `param array` $criteria Search criteria [Optional]
* `return int`
### haveInDatabase
Inserts an SQL record into a database. This record will be erased after the test.
```
<?php
$I->haveInDatabase('users', array('name' => 'miles', 'email' => '[email protected]'));
?>
```
* `param string` $table
* `param array` $data
* `return integer` $id
### performInDatabase
Can be used with a callback if you don’t want to change the current database in your test.
```
<?php
$I->seeNumRecords(2, 'users'); //executed on default database
$I->performInDatabase('db_books', function($I) {
$I->seeNumRecords(30, 'books'); //executed on db_books database
});
$I->seeNumRecords(2, 'users'); //executed on default database
```
List of actions can be pragmatically built using `Codeception\Util\ActionSequence`:
```
<?php
$I->performInDatabase('db_books', ActionSequence::build()
->seeNumRecords(30, 'books')
);
```
Alternatively an array can be used:
```
$I->performInDatabase('db_books', ['seeNumRecords' => [30, 'books']]);
```
Choose the syntax you like the most and use it,
Actions executed from array or ActionSequence will print debug output for actions, and adds an action name to exception on failure.
* `param` $databaseKey
* `param \Codeception\Util\ActionSequence|array|callable` $actions @throws ModuleConfigException
### seeInDatabase
Asserts that a row with the given column values exists. Provide table name and column values.
```
<?php
$I->seeInDatabase('users', ['name' => 'Davert', 'email' => '[email protected]']);
```
Fails if no such user found.
Comparison expressions can be used as well:
```
<?php
$I->seeInDatabase('posts', ['num_comments >=' => '0']);
$I->seeInDatabase('users', ['email like' => '[email protected]']);
```
Supported operators: `<`, `>`, `>=`, `<=`, `!=`, `like`.
* `param string` $table
* `param array` $criteria
### seeNumRecords
Asserts that the given number of records were found in the database.
```
<?php
$I->seeNumRecords(1, 'users', ['name' => 'davert'])
?>
```
* `param int` $expectedNumber Expected number
* `param string` $table Table name
* `param array` $criteria Search criteria [Optional]
### updateInDatabase
Update an SQL record into a database.
```
<?php
$I->updateInDatabase('users', array('isAdmin' => true), array('email' => '[email protected]'));
?>
```
* `param string` $table
* `param array` $data
* `param array` $criteria
codeception MongoDb MongoDb
=======
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-mongodb
```
Alternatively, you can enable `MongoDb` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Works with MongoDb database.
The most important function of this module is cleaning database before each test. To have your database properly cleaned you should configure it to access the database.
In order to have your database populated with data you need a valid js file with data (of the same style which can be fed up to mongo binary) File can be generated by RockMongo export command You can also use directory, generated by
```
mongodump
```
tool or it’s
```
.tar.gz
```
archive (not available for Windows systems), generated by
```
tar -czf <archive_file_name>.tar.gz <path_to dump directory>
```
. Just put it in
```
tests/_data
```
dir (by default) and specify path to it in config. Next time after database is cleared all your data will be restored from dump. The DB preparation should as following:
* clean database
* system collection system.users should contain the user which will be authenticated while script performs DB operations
Connection is done by MongoDb driver, which is stored in Codeception\Lib\Driver namespace. Check out the driver if you get problems loading dumps and cleaning databases.
HINT: This module can be used with [Mongofill](https://github.com/mongofill/mongofill) library which is Mongo client written in PHP without extension.
Status
------
* Maintainer: **judgedim**, **davert**
* Stability: **beta**
* Contact: [email protected]
*Please review the code of non-stable modules and provide patches if you have issues.*
Config
------
* dsn *required* - MongoDb DSN with the db name specified at the end of the host after slash
* user *required* - user to access database
* password *required* - password
* dump\_type *required* - type of dump. One of ‘js’ (MongoDb::DUMP\_TYPE\_JS), ‘mongodump’ (MongoDb::DUMP\_TYPE\_MONGODUMP) or ‘mongodump-tar-gz’ (MongoDb::DUMP\_TYPE\_MONGODUMP\_TAR\_GZ). default: MongoDb::DUMP\_TYPE\_JS).
* dump - path to database dump
* populate: true - should the dump be loaded before test suite is started.
* cleanup: true - should the dump be reloaded after each test. Boolean or ‘dirty’. If cleanup is set to ‘dirty’, the dump is only reloaded if any data has been written to the db during a test. This is checked using the [dbHash](https://docs.mongodb.com/manual/reference/command/dbHash/) command.
Actions
-------
### dontSeeInCollection
Checks if collection doesn’t contain an item.
```
<?php
$I->dontSeeInCollection('users', array('name' => 'miles'));
```
* `param` $collection
* `param array` $criteria
### grabCollectionCount
Grabs the documents count from a collection
```
<?php
$count = $I->grabCollectionCount('users');
// or
$count = $I->grabCollectionCount('users', array('isAdmin' => true));
```
* `param` $collection
* `param array` $criteria
* `return integer`
### grabFromCollection
Grabs a data from collection
```
<?php
$user = $I->grabFromCollection('users', array('name' => 'miles'));
```
* `param` $collection
* `param array` $criteria
* `return array`
### haveInCollection
Inserts data into collection
```
<?php
$I->haveInCollection('users', array('name' => 'John', 'email' => '[email protected]'));
$user_id = $I->haveInCollection('users', array('email' => '[email protected]'));
```
* `param` $collection
* `param array` $data
### seeElementIsArray
Asserts that an element in a collection exists and is an Array
```
<?php
$I->seeElementIsArray('users', array('name' => 'John Doe') , 'data.skills');
```
* `param String` $collection
* `param Array` $criteria
* `param String` $elementToCheck
### seeElementIsObject
Asserts that an element in a collection exists and is an Object
```
<?php
$I->seeElementIsObject('users', array('name' => 'John Doe') , 'data');
```
* `param String` $collection
* `param Array` $criteria
* `param String` $elementToCheck
### seeInCollection
Checks if collection contains an item.
```
<?php
$I->seeInCollection('users', array('name' => 'miles'));
```
* `param` $collection
* `param array` $criteria
### seeNumElementsInCollection
Count number of records in a collection
```
<?php
$I->seeNumElementsInCollection('users', 2);
$I->seeNumElementsInCollection('users', 1, array('name' => 'miles'));
```
* `param` $collection
* `param integer` $expected
* `param array` $criteria
### useDatabase
Specify the database to use
```
<?php
$I->useDatabase('db_1');
```
* `param` $dbName
| programming_docs |
codeception Asserts Asserts
=======
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-asserts
```
Alternatively, you can enable `Asserts` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Special module for using asserts in your tests.
Actions
-------
### assertArrayHasKey
Asserts that an array has a specified key.
* `param int|string` $key
* `param array|ArrayAccess` $array
* `param string` $message
### assertArrayNotHasKey
Asserts that an array does not have a specified key.
* `param int|string` $key
* `param array|ArrayAccess` $array
* `param string` $message
### assertClassHasAttribute
Asserts that a class has a specified attribute.
* `param string` $attributeName
* `param string` $className
* `param string` $message
### assertClassHasStaticAttribute
Asserts that a class has a specified static attribute.
* `param string` $attributeName
* `param string` $className
* `param string` $message
### assertClassNotHasAttribute
Asserts that a class does not have a specified attribute.
* `param string` $attributeName
* `param string` $className
* `param string` $message
### assertClassNotHasStaticAttribute
Asserts that a class does not have a specified static attribute.
* `param string` $attributeName
* `param string` $className
* `param string` $message
### assertContains
Asserts that a haystack contains a needle.
* `param` $needle
* `param` $haystack
* `param string` $message
### assertContainsEquals
* `param` $needle
* `param` $haystack
* `param string` $message
### assertContainsOnly
Asserts that a haystack contains only values of a given type.
* `param string` $type
* `param` $haystack
* `param bool|null` $isNativeType
* `param string` $message
### assertContainsOnlyInstancesOf
Asserts that a haystack contains only instances of a given class name.
* `param string` $className
* `param` $haystack
* `param string` $message
### assertCount
Asserts the number of elements of an array, Countable or Traversable.
* `param int` $expectedCount
* `param Countable|iterable` $haystack
* `param string` $message
### assertDirectoryDoesNotExist
Asserts that a directory does not exist.
* `param string` $directory
* `param string` $message
### assertDirectoryExists
Asserts that a directory exists.
* `param string` $directory
* `param string` $message
### assertDirectoryIsNotReadable
Asserts that a directory exists and is not readable.
* `param string` $directory
* `param string` $message
### assertDirectoryIsNotWritable
Asserts that a directory exists and is not writable.
* `param string` $directory
* `param string` $message
### assertDirectoryIsReadable
Asserts that a directory exists and is readable.
* `param string` $directory
* `param string` $message
### assertDirectoryIsWritable
Asserts that a directory exists and is writable.
* `param string` $directory
* `param string` $message
### assertDoesNotMatchRegularExpression
Asserts that a string does not match a given regular expression.
* `param string` $pattern
* `param string` $string
* `param string` $message
### assertEmpty
Asserts that a variable is empty.
* `param` $actual
* `param string` $message
### assertEquals
Asserts that two variables are equal.
* `param` $expected
* `param` $actual
* `param string` $message
### assertEqualsCanonicalizing
Asserts that two variables are equal (canonicalizing).
* `param` $expected
* `param` $actual
* `param string` $message
### assertEqualsIgnoringCase
Asserts that two variables are equal (ignoring case).
* `param` $expected
* `param` $actual
* `param string` $message
### assertEqualsWithDelta
Asserts that two variables are equal (with delta).
* `param` $expected
* `param` $actual
* `param float` $delta
* `param string` $message
### assertFalse
Asserts that a condition is false.
* `param` $condition
* `param string` $message
### assertFileDoesNotExist
Asserts that a file does not exist.
* `param string` $filename
* `param string` $message
### assertFileEquals
Asserts that the contents of one file is equal to the contents of another file.
* `param string` $expected
* `param string` $actual
* `param string` $message
### assertFileEqualsCanonicalizing
Asserts that the contents of one file is equal to the contents of another file (canonicalizing).
* `param` $expected
* `param` $actual
* `param string` $message
### assertFileEqualsIgnoringCase
Asserts that the contents of one file is equal to the contents of another file (ignoring case).
* `param` $expected
* `param` $actual
* `param string` $message
### assertFileExists
Asserts that a file exists.
* `param string` $filename
* `param string` $message
### assertFileIsNotReadable
Asserts that a file exists and is not readable.
* `param string` $file
* `param string` $message
### assertFileIsNotWritable
Asserts that a file exists and is not writable.
* `param string` $file
* `param string` $message
### assertFileIsReadable
Asserts that a file exists and is readable.
* `param string` $file
* `param string` $message
### assertFileIsWritable
Asserts that a file exists and is writable.
* `param string` $file
* `param string` $message
### assertFileNotEquals
Asserts that the contents of one file is not equal to the contents of another file.
* `param` $expected
* `param` $actual
* `param string` $message
### assertFileNotEqualsCanonicalizing
Asserts that the contents of one file is not equal to the contents of another file (canonicalizing).
* `param` $expected
* `param` $actual
* `param string` $message
### assertFileNotEqualsIgnoringCase
Asserts that the contents of one file is not equal to the contents of another file (ignoring case).
* `param` $expected
* `param` $actual
* `param string` $message
### assertFileNotExists
Asserts that a file does not exist.
* `param string` $filename
* `param string` $message
### assertFinite
Asserts that a variable is finite.
* `param` $actual
* `param string` $message
### assertGreaterOrEquals
Asserts that a value is greater than or equal to another value.
* `param` $expected
* `param` $actual
* `param string` $message
### assertGreaterThan
Asserts that a value is greater than another value.
* `param` $expected
* `param` $actual
* `param string` $message
### assertGreaterThanOrEqual
Asserts that a value is greater than or equal to another value.
* `param` $expected
* `param` $actual
* `param string` $message
### assertInfinite
Asserts that a variable is infinite.
* `param` $actual
* `param string` $message
### assertInstanceOf
Asserts that a variable is of a given type.
* `param` $expected
* `param` $actual
* `param string` $message
### assertIsArray
Asserts that a variable is of type array.
* `param` $actual
* `param string` $message
### assertIsBool
Asserts that a variable is of type bool.
* `param` $actual
* `param string` $message
### assertIsCallable
Asserts that a variable is of type callable.
* `param` $actual
* `param string` $message
### assertIsClosedResource
Asserts that a variable is of type resource and is closed.
* `param` $actual
* `param string` $message
### assertIsEmpty
Asserts that a variable is empty.
* `param` $actual
* `param string` $message
### assertIsFloat
Asserts that a variable is of type float.
* `param` $actual
* `param string` $message
### assertIsInt
Asserts that a variable is of type int.
* `param` $actual
* `param string` $message
### assertIsIterable
Asserts that a variable is of type iterable.
* `param` $actual
* `param string` $message
### assertIsNotArray
Asserts that a variable is not of type array.
* `param` $actual
* `param string` $message
### assertIsNotBool
Asserts that a variable is not of type bool.
* `param` $actual
* `param string` $message
### assertIsNotCallable
Asserts that a variable is not of type callable.
* `param` $actual
* `param string` $message
### assertIsNotClosedResource
Asserts that a variable is not of type resource.
* `param` $actual
* `param string` $message
### assertIsNotFloat
Asserts that a variable is not of type float.
* `param` $actual
* `param string` $message
### assertIsNotInt
Asserts that a variable is not of type int.
* `param` $actual
* `param string` $message
### assertIsNotIterable
Asserts that a variable is not of type iterable.
* `param` $actual
* `param string` $message
### assertIsNotNumeric
Asserts that a variable is not of type numeric.
* `param` $actual
* `param string` $message
### assertIsNotObject
Asserts that a variable is not of type object.
* `param` $actual
* `param string` $message
### assertIsNotReadable
Asserts that a file/dir exists and is not readable.
* `param string` $filename
* `param string` $message
### assertIsNotResource
Asserts that a variable is not of type resource.
* `param` $actual
* `param string` $message
### assertIsNotScalar
Asserts that a variable is not of type scalar.
* `param` $actual
* `param string` $message
### assertIsNotString
Asserts that a variable is not of type string.
* `param` $actual
* `param string` $message
### assertIsNotWritable
Asserts that a file/dir exists and is not writable.
* `param` $filename
* `param string` $message
### assertIsNumeric
Asserts that a variable is of type numeric.
* `param` $actual
* `param string` $message
### assertIsObject
Asserts that a variable is of type object.
* `param` $actual
* `param string` $message
### assertIsReadable
Asserts that a file/dir is readable.
* `param` $filename
* `param string` $message
### assertIsResource
Asserts that a variable is of type resource.
* `param` $actual
* `param string` $message
### assertIsScalar
Asserts that a variable is of type scalar.
* `param` $actual
* `param string` $message
### assertIsString
Asserts that a variable is of type string.
* `param` $actual
* `param string` $message
### assertIsWritable
Asserts that a file/dir exists and is writable.
* `param` $filename
* `param string` $message
### assertJson
Asserts that a string is a valid JSON string.
* `param string` $actualJson
* `param string` $message
### assertJsonFileEqualsJsonFile
Asserts that two JSON files are equal.
* `param string` $expectedFile
* `param string` $actualFile
* `param string` $message
### assertJsonFileNotEqualsJsonFile
Asserts that two JSON files are not equal.
* `param string` $expectedFile
* `param string` $actualFile
* `param string` $message
### assertJsonStringEqualsJsonFile
Asserts that the generated JSON encoded object and the content of the given file are equal.
* `param string` $expectedFile
* `param string` $actualJson
* `param string` $message
### assertJsonStringEqualsJsonString
Asserts that two given JSON encoded objects or arrays are equal.
* `param string` $expectedJson
* `param string` $actualJson
* `param string` $message
### assertJsonStringNotEqualsJsonFile
Asserts that the generated JSON encoded object and the content of the given file are not equal.
* `param string` $expectedFile
* `param string` $actualJson
* `param string` $message
### assertJsonStringNotEqualsJsonString
Asserts that two given JSON encoded objects or arrays are not equal.
* `param string` $expectedJson
* `param string` $actualJson
* `param string` $message
### assertLessOrEquals
Asserts that a value is smaller than or equal to another value.
* `param` $expected
* `param` $actual
* `param string` $message
### assertLessThan
Asserts that a value is smaller than another value.
* `param` $expected
* `param` $actual
* `param string` $message
### assertLessThanOrEqual
Asserts that a value is smaller than or equal to another value.
* `param` $expected
* `param` $actual
* `param string` $message
### assertMatchesRegularExpression
Asserts that a string matches a given regular expression.
* `param string` $pattern
* `param string` $string
* `param string` $message
### assertNan
Asserts that a variable is nan.
* `param` $actual
* `param string` $message
### assertNotContains
Asserts that a haystack does not contain a needle.
* `param` $needle
* `param` $haystack
* `param string` $message
### assertNotContainsEquals
**not documented**
### assertNotContainsOnly
Asserts that a haystack does not contain only values of a given type.
* `param string` $type
* `param` $haystack
* `param bool|null` $isNativeType
* `param string` $message
### assertNotCount
Asserts the number of elements of an array, Countable or Traversable.
* `param int` $expectedCount
* `param Countable|iterable` $haystack
* `param string` $message
### assertNotEmpty
Asserts that a variable is not empty.
* `param` $actual
* `param string` $message
### assertNotEquals
Asserts that two variables are not equal.
* `param` $expected
* `param` $actual
* `param string` $message
### assertNotEqualsCanonicalizing
Asserts that two variables are not equal (canonicalizing).
* `param` $expected
* `param` $actual
* `param string` $message
### assertNotEqualsIgnoringCase
Asserts that two variables are not equal (ignoring case).
* `param` $expected
* `param` $actual
* `param string` $message
### assertNotEqualsWithDelta
Asserts that two variables are not equal (with delta).
* `param` $expected
* `param` $actual
* `param float` $delta
* `param string` $message
### assertNotFalse
Asserts that a condition is not false.
* `param` $condition
* `param string` $message
### assertNotInstanceOf
Asserts that a variable is not of a given type.
* `param` $expected
* `param` $actual
* `param string` $message
### assertNotNull
Asserts that a variable is not null.
* `param` $actual
* `param string` $message
### assertNotRegExp
Asserts that a string does not match a given regular expression.
* `param string` $pattern
* `param string` $string
* `param string` $message
### assertNotSame
Asserts that two variables do not have the same type and value.
* `param` $expected
* `param` $actual
* `param string` $message
### assertNotSameSize
Assert that the size of two arrays (or `Countable` or `Traversable` objects) is not the same.
* `param Countable|iterable` $expected
* `param Countable|iterable` $actual
* `param string` $message
### assertNotTrue
Asserts that a condition is not true.
* `param` $condition
* `param string` $message
### assertNull
Asserts that a variable is null.
* `param` $actual
* `param string` $message
### assertObjectHasAttribute
Asserts that an object has a specified attribute.
* `param string` $attributeName
* `param object` $object
* `param string` $message
### assertObjectNotHasAttribute
Asserts that an object does not have a specified attribute.
* `param string` $attributeName
* `param object` $object
* `param string` $message
### assertRegExp
Asserts that a string matches a given regular expression.
* `param string` $pattern
* `param string` $string
* `param string` $message
### assertSame
Asserts that two variables have the same type and value.
* `param` $expected
* `param` $actual
* `param string` $message
### assertSameSize
Assert that the size of two arrays (or `Countable` or `Traversable` objects) is the same.
* `param Countable|iterable` $expected
* `param Countable|iterable` $actual
* `param string` $message
### assertStringContainsString
* `param string` $needle
* `param string` $haystack
* `param string` $message
### assertStringContainsStringIgnoringCase
**not documented**
### assertStringEndsNotWith
Asserts that a string ends not with a given suffix.
* `param string` $suffix
* `param string` $string
* `param string` $message
### assertStringEndsWith
Asserts that a string ends with a given suffix.
* `param string` $suffix
* `param string` $string
* `param string` $message
### assertStringEqualsFile
Asserts that the contents of a string is equal to the contents of a file.
* `param string` $expectedFile
* `param string` $actualString
* `param string` $message
### assertStringEqualsFileCanonicalizing
Asserts that the contents of a string is equal to the contents of a file (canonicalizing).
* `param string` $expectedFile
* `param string` $actualString
* `param string` $message
### assertStringEqualsFileIgnoringCase
Asserts that the contents of a string is equal to the contents of a file (ignoring case).
* `param string` $expectedFile
* `param string` $actualString
* `param string` $message
### assertStringMatchesFormat
Asserts that a string matches a given format string.
* `param string` $format
* `param string` $string
* `param string` $message
### assertStringMatchesFormatFile
Asserts that a string matches a given format file.
* `param string` $formatFile
* `param string` $string
* `param string` $message
### assertStringNotContainsString
* `param string` $needle
* `param string` $haystack
* `param string` $message
### assertStringNotContainsStringIgnoringCase
* `param string` $needle
* `param string` $haystack
* `param string` $message
### assertStringNotEqualsFile
Asserts that the contents of a string is not equal to the contents of a file.
* `param string` $expectedFile
* `param string` $actualString
* `param string` $message
### assertStringNotEqualsFileCanonicalizing
Asserts that the contents of a string is not equal to the contents of a file (canonicalizing).
* `param string` $expectedFile
* `param string` $actualString
* `param string` $message
### assertStringNotEqualsFileIgnoringCase
Asserts that the contents of a string is not equal to the contents of a file (ignoring case).
* `param string` $expectedFile
* `param string` $actualString
* `param string` $message
### assertStringNotMatchesFormat
Asserts that a string does not match a given format string.
* `param string` $format
* `param string` $string
* `param string` $message
### assertStringNotMatchesFormatFile
Asserts that a string does not match a given format string.
* `param string` $formatFile
* `param string` $string
* `param string` $message
### assertStringStartsNotWith
Asserts that a string starts not with a given prefix.
* `param string` $prefix
* `param string` $string
* `param string` $message
### assertStringStartsWith
Asserts that a string starts with a given prefix.
* `param string` $prefix
* `param string` $string
* `param string` $message
### assertThat
Evaluates a PHPUnit\Framework\Constraint matcher object.
* `param` $value
* `param Constraint` $constraint
* `param string` $message
### assertThatItsNot
Evaluates a PHPUnit\Framework\Constraint matcher object.
* `param` $value
* `param Constraint` $constraint
* `param string` $message
### assertTrue
Asserts that a condition is true.
* `param` $condition
* `param string` $message
### assertXmlFileEqualsXmlFile
Asserts that two XML files are equal.
* `param string` $expectedFile
* `param string` $actualFile
* `param string` $message
### assertXmlFileNotEqualsXmlFile
Asserts that two XML files are not equal.
* `param string` $expectedFile
* `param string` $actualFile
* `param string` $message
### assertXmlStringEqualsXmlFile
Asserts that two XML documents are equal.
* `param string` $expectedFile
* `param DOMDocument|string` $actualXml
* `param string` $message
### assertXmlStringEqualsXmlString
Asserts that two XML documents are equal.
* `param DOMDocument|string` $expectedXml
* `param DOMDocument|string` $actualXml
* `param string` $message
### assertXmlStringNotEqualsXmlFile
Asserts that two XML documents are not equal.
* `param string` $expectedFile
* `param DOMDocument|string` $actualXml
* `param string` $message
### assertXmlStringNotEqualsXmlString
Asserts that two XML documents are not equal.
* `param DOMDocument|string` $expectedXml
* `param DOMDocument|string` $actualXml
* `param string` $message
### expectException
Handles and checks exception called inside callback function. Either exception class name or exception instance should be provided.
```
<?php
$I->expectException(MyException::class, function() {
$this->doSomethingBad();
});
$I->expectException(new MyException(), function() {
$this->doSomethingBad();
});
```
If you want to check message or exception code, you can pass them with exception instance:
```
<?php
// will check that exception MyException is thrown with "Don't do bad things" message
$I->expectException(new MyException("Don't do bad things"), function() {
$this->doSomethingBad();
});
```
@deprecated Use expectThrowable() instead
* `param \Exception|string` $exception
* `param callable` $callback
### expectThrowable
Handles and checks throwables (Exceptions/Errors) called inside the callback function. Either throwable class name or throwable instance should be provided.
```
<?php
$I->expectThrowable(MyThrowable::class, function() {
$this->doSomethingBad();
});
$I->expectThrowable(new MyException(), function() {
$this->doSomethingBad();
});
```
If you want to check message or throwable code, you can pass them with throwable instance:
```
<?php
// will check that throwable MyError is thrown with "Don't do bad things" message
$I->expectThrowable(new MyError("Don't do bad things"), function() {
$this->doSomethingBad();
});
```
* `param \Throwable|string` $throwable
* `param callable` $callback
### fail
Fails a test with the given message.
* `param string` $message
### markTestIncomplete
Mark the test as incomplete.
* `param string` $message
### markTestSkipped
Mark the test as skipped.
* `param string` $message
| programming_docs |
codeception Laminas Laminas
=======
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-laminas
```
Alternatively, you can enable `Laminas` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module allows you to run tests inside the Laminas Project. Uses `tests/application.config.php` config file by default.
Status
------
* Maintainer: **Naktibalda**
* Stability: **stable**
Config
------
* config: relative path to config file (default: `tests/application.config.php`)
* em\_service: ‘Doctrine\ORM\EntityManager’ - use the stated EntityManager to pair with Doctrine Module.
Public Properties
-----------------
* application - instance of `\Laminas\Mvc\ApplicationInterface`
* db - instance of `\Laminas\Db\Adapter\AdapterInterface`
* client - BrowserKit client
Parts
-----
* services - allows to use grabServiceFromContainer and addServiceToContainer with WebDriver or PhpBrowser modules.
Usage example:
```
actor: AcceptanceTester
modules:
enabled:
- Laminas:
part: services
- Doctrine2:
depends: Laminas
- WebDriver:
url: http://your-url.com
browser: phantomjs
```
Actions
-------
### \_findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$els = $this->getModule('Laminas')->_findElements('.items');
$els = $this->getModule('Laminas')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('Laminas')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return array` of interactive elements
### \_getResponseContent
*hidden API method, expected to be used from Helper classes*
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
```
<?php
// in Helper class
public function seeResponseContains($text)
{
$this->assertStringContainsString($text, $this->getModule('Laminas')->_getResponseContent(), "response contains");
}
```
* `return string` @throws ModuleException
### \_loadPage
*hidden API method, expected to be used from Helper classes*
Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step.
```
<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
$this->getModule('Laminas')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
```
* `param string` $method
* `param string` $uri
* `param string` $content
### \_request
*hidden API method, expected to be used from Helper classes*
Send custom request to a backend using method, uri, parameters, etc. Use it in Helpers to create special request actions, like accessing API Returns a string with response body.
```
<?php
// in Helper class
public function createUserByApi($name) {
$userData = $this->getModule('Laminas')->_request('POST', '/api/v1/users', ['name' => $name]);
$user = json_decode($userData);
return $user->id;
}
```
Does not load the response into the module so you can’t interact with response page (click, fill forms). To load arbitrary page for interaction, use `_loadPage` method.
* `param string` $method
* `param string` $uri
* `param string` $content
* `return string` @throws ExternalUrlException @see `_loadPage`
### \_savePageSource
*hidden API method, expected to be used from Helper classes*
Saves page source of to a file
```
$this->getModule('Laminas')->_savePageSource(codecept_output_dir().'page.html');
```
* `param` $filename
### addFactoryToContainer
Adds factory to a Laminas container
* `param string` $name
* `param string|callable|FactoryInterface` $factory
* `return void`
* `[Part]` services
### addServiceToContainer
Adds service to a Laminas container
* `[Part]` services
* `param array|object` $service
### amHttpAuthenticated
Authenticates user for HTTP\_AUTH
* `param string` $username
* `param string` $password
### amOnPage
Opens the page for the given relative URI.
```
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
```
* `param string` $page
### amOnRoute
Opens web page using route name and parameters.
```
<?php
$I->amOnRoute('posts.create');
$I->amOnRoute('posts.show', array('id' => 34));
```
### attachFile
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
```
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
```
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### click
Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
```
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### deleteHeader
Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
```
* `param string` $name the name of the header to delete.
### dontSee
Checks that the current page doesn’t contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region.
```
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will ignore strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
```
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn’t a cookie with the given name. You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn’t equal the given string. Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
```
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn’t match the given regular expression.
```
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page. You can also specify expected attributes of this element.
```
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeInCurrentUrl
Checks that the current URI doesn’t contain the given string.
```
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### dontSeeInField
Checks that an input field or textarea doesn’t contain the given value. For fuzzy locators, the field is matched by label text, CSS and XPath.
```
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
```
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn’t been assigned any one of many values, an array can be passed as the value:
```
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn’t contain a link with the given string. If the second parameter is given, only links with a matching “href” attribute will be checked.
```
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param string` $text
* `param string` $url optional
### dontSeeOptionIsSelected
Checks that the given option is not selected.
```
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### dontSeeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->dontSeeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### fillField
Fills a text field or textarea with the given string.
```
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], '[email protected]');
?>
```
* `param` $field
* `param` $value
### followRedirect
Follow pending redirect if there is one.
```
<?php
$I->followRedirect();
```
### grabAttributeFrom
Grabs the value of the given attribute value from the given element. Fails if element is not found.
```
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabCookie
Grabs a cookie value. You can set additional cookie params like `domain`, `path` in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try `$I->wait(0.1)`.
* `param` $cookie
* `param array` $params
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
```
<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param string` $uri optional
### grabMultiple
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
```
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return string[]`
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return string` Current page source code.
### grabServiceFromContainer
Grabs a service from a Laminas container. Recommended to use for unit testing.
```
<?php
$em = $I->grabServiceFromContainer('Doctrine\ORM\EntityManager');
```
* `[Part]` services
### grabTextFrom
Finds and returns the text contents of the given element. If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
```
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
* `param` $field
* `return array|mixed|null|string`
### haveHttpHeader
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
```
To use special chars in Header Key use HTML Character Entities: Example: Header with underscore - ‘Client\_Id’ should be represented as - ‘Client\_Id’ or ‘Client\_Id’
```
<?php
$I->haveHttpHeader('Client_Id', 'Codeception');
```
* `param string` $name the name of the request header
* `param string` $value the value to set it to for subsequent requests
### haveServerParameter
Sets SERVER parameter valid for all next requests.
```
$I->haveServerParameter('name', 'value');
```
* `param string` $name
* `param string` $value
### makeHtmlSnapshot
Use this method within an [interactive pause](../02-gettingstarted#Interactive-Pause) to save the HTML source code of the current page.
```
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
```
* `param null` $name
### moveBack
Moves back in history.
* `param int` $numberOfSteps (default value 1)
### resetCookie
Unsets cookie with the given name. You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.
```
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->see('strong')` will return true for strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
```
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set. You can set additional cookie params like `domain`, `path` as array passed in last argument.
```
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentRouteIs
Checks that current url matches route.
```
<?php
$I->seeCurrentRouteIs('posts.index');
$I->seeCurrentRouteIs('posts.show', ['id' => 8]));
```
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string. Unlike `seeInCurrentUrl`, this only matches the full URL.
```
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
```
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### seeElement
Checks that the given element exists on the page and is visible. You can also specify expected attributes of this element.
```
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
### seeInCurrentUrl
Checks that current URI contains the given string.
```
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### seeInField
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value. Fields are matched by label text, the “name” attribute, CSS, or XPath.
```
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
```
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
```
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
```
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there’s a link with the specified text. Give a full URL as the second parameter to match links with that exact URL.
```
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param string` $text
* `param string` $url optional
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
```
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected int or int[]
### seeOptionIsSelected
Checks that the given option is selected.
```
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### seePageNotFound
Asserts that current page has 404 response status code.
### seeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->seeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### seeResponseCodeIsBetween
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
* `param int` $from
* `param int` $to
### seeResponseCodeIsClientError
Checks that the response code is 4xx
### seeResponseCodeIsRedirection
Checks that the response code 3xx
### seeResponseCodeIsServerError
Checks that the response code is 5xx
### seeResponseCodeIsSuccessful
Checks that the response code 2xx
### selectOption
Selects an option in a select tag or in radio button group.
```
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
```
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
```
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### sendAjaxGetRequest
Sends an ajax GET request with the passed parameters. See `sendAjaxPostRequest()`
* `param` $uri
* `param` $params
### sendAjaxPostRequest
Sends an ajax POST request with the passed parameters. The appropriate HTTP header is added automatically: `X-Requested-With: XMLHttpRequest` Example:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['task' => 'lorem ipsum']);
```
Some frameworks (e.g. Symfony) create field names in the form of an “array”: `<input type="text" name="form[task]">` In this case you need to pass the fields like this:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['form' => [
'task' => 'lorem ipsum',
'category' => 'miscellaneous',
]]);
```
* `param string` $uri
* `param array` $params
### sendAjaxRequest
Sends an ajax request, using the passed HTTP method. See `sendAjaxPostRequest()` Example:
```
<?php
$I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
```
* `param` $method
* `param` $uri
* `param array` $params
### setCookie
Sets a cookie with the given name and value. You can set additional cookie params like `domain`, `path`, `expires`, `secure` in array passed as last argument.
```
<?php
$I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
?>
```
* `param` $name
* `param` $val
* `param array` $params
### setMaxRedirects
Sets the maximum number of redirects that the Client can follow.
```
<?php
$I->setMaxRedirects(2);
```
* `param int` $maxRedirects
### setServerParameters
Sets SERVER parameters valid for all next requests. this will remove old ones.
```
$I->setServerParameters([]);
```
### startFollowingRedirects
Enables automatic redirects to be followed by the client.
```
<?php
$I->startFollowingRedirects();
```
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client.
```
<?php
$I->stopFollowingRedirects();
```
### submitForm
Submits the given form on the page, with the given form values. Pass the form field’s values as an array in the second parameter.
Although this function can be used as a short-hand version of `fillField()`, `selectOption()`, `click()` etc. it has some important differences:
* Only field *names* may be used, not CSS/XPath selectors nor field labels
* If a field is sent to this function that does *not* exist on the page, it will silently be added to the HTTP request. This is helpful for testing some types of forms, but be aware that you will *not* get an exception like you would if you called `fillField()` or `selectOption()` with a missing field.
Fields that are not provided will be filled by their values from the page, or from any previous calls to `fillField()`, `selectOption()` etc. You don’t need to click the ‘Submit’ button afterwards. This command itself triggers the request to form’s action.
You can optionally specify which button’s value to include in the request with the last parameter (as an alternative to explicitly setting its value in the second parameter), as button values are not otherwise included in the request.
Examples:
```
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample “Sign Up” form:
```
<form id="userForm">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Subscribe to our newsletter?
<input type="checkbox" name="user[newsletter]" value="1" checked="checked" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
],
'submitButton'
);
```
Note that “2” will be the submitted value for the “plan” field, as it is the selected option.
To uncheck the pre-checked checkbox “newsletter”, call `$I->uncheckOption(['name' => 'user[newsletter]']);` *before*, then submit the form as shown here (i.e. without the “newsletter” field in the `$params` array).
You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
]
);
```
This function works well when paired with `seeInFormFields()` for quickly testing CRUD interfaces and form validation logic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);
```
Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean `true`/`false` which will be replaced by the checkbox’s value in the DOM.
```
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false
],
'multiselect' => [
'first option value',
'second option value'
]
]);
```
Mixing string and boolean values for a checkbox’s value is not supported and may produce unexpected results.
Field names ending in `[]` must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:
```
<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```
<?php
// This way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
* `param` $selector
* `param` $params
* `param` $button
### switchToIframe
Switch to iframe or frame on the page.
Example:
```
<iframe name="another_frame" src="http://example.com">
```
```
<?php
# switch to iframe
$I->switchToIframe("another_frame");
```
* `param string` $name
### uncheckOption
Unticks a checkbox.
```
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
| programming_docs |
codeception Laminas Laminas
=======
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-laminas
```
Alternatively, you can enable `Laminas` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module allows you to run tests inside the Laminas Project. Uses `tests/application.config.php` config file by default.
Status
------
* Maintainer: **Naktibalda**
* Stability: **stable**
Config
------
* config: relative path to config file (default: `tests/application.config.php`)
* em\_service: ‘Doctrine\ORM\EntityManager’ - use the stated EntityManager to pair with Doctrine Module.
Public Properties
-----------------
* application - instance of `\Laminas\Mvc\ApplicationInterface`
* db - instance of `\Laminas\Db\Adapter\AdapterInterface`
* client - BrowserKit client
Parts
-----
* services - allows to use grabServiceFromContainer and addServiceToContainer with WebDriver or PhpBrowser modules.
Usage example:
```
actor: AcceptanceTester
modules:
enabled:
- Laminas:
part: services
- Doctrine2:
depends: Laminas
- WebDriver:
url: http://your-url.com
browser: phantomjs
```
Actions
-------
### \_findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$els = $this->getModule('Laminas')->_findElements('.items');
$els = $this->getModule('Laminas')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('Laminas')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return array` of interactive elements
### \_getResponseContent
*hidden API method, expected to be used from Helper classes*
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
```
<?php
// in Helper class
public function seeResponseContains($text)
{
$this->assertStringContainsString($text, $this->getModule('Laminas')->_getResponseContent(), "response contains");
}
```
* `return string` @throws ModuleException
### \_loadPage
*hidden API method, expected to be used from Helper classes*
Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step.
```
<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
$this->getModule('Laminas')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
```
* `param string` $method
* `param string` $uri
* `param string` $content
### \_request
*hidden API method, expected to be used from Helper classes*
Send custom request to a backend using method, uri, parameters, etc. Use it in Helpers to create special request actions, like accessing API Returns a string with response body.
```
<?php
// in Helper class
public function createUserByApi($name) {
$userData = $this->getModule('Laminas')->_request('POST', '/api/v1/users', ['name' => $name]);
$user = json_decode($userData);
return $user->id;
}
```
Does not load the response into the module so you can’t interact with response page (click, fill forms). To load arbitrary page for interaction, use `_loadPage` method.
* `param string` $method
* `param string` $uri
* `param string` $content
* `return string` @throws ExternalUrlException @see `_loadPage`
### \_savePageSource
*hidden API method, expected to be used from Helper classes*
Saves page source of to a file
```
$this->getModule('Laminas')->_savePageSource(codecept_output_dir().'page.html');
```
* `param` $filename
### addFactoryToContainer
Adds factory to a Laminas container
* `param string` $name
* `param string|callable|FactoryInterface` $factory
* `return void`
* `[Part]` services
### addServiceToContainer
Adds service to a Laminas container
* `[Part]` services
* `param array|object` $service
### amHttpAuthenticated
Authenticates user for HTTP\_AUTH
* `param string` $username
* `param string` $password
### amOnPage
Opens the page for the given relative URI.
```
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
```
* `param string` $page
### amOnRoute
Opens web page using route name and parameters.
```
<?php
$I->amOnRoute('posts.create');
$I->amOnRoute('posts.show', array('id' => 34));
```
### attachFile
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
```
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
```
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### click
Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
```
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### deleteHeader
Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
```
* `param string` $name the name of the header to delete.
### dontSee
Checks that the current page doesn’t contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region.
```
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will ignore strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
```
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn’t a cookie with the given name. You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn’t equal the given string. Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
```
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn’t match the given regular expression.
```
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page. You can also specify expected attributes of this element.
```
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeInCurrentUrl
Checks that the current URI doesn’t contain the given string.
```
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### dontSeeInField
Checks that an input field or textarea doesn’t contain the given value. For fuzzy locators, the field is matched by label text, CSS and XPath.
```
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
```
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn’t been assigned any one of many values, an array can be passed as the value:
```
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn’t contain a link with the given string. If the second parameter is given, only links with a matching “href” attribute will be checked.
```
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param string` $text
* `param string` $url optional
### dontSeeOptionIsSelected
Checks that the given option is not selected.
```
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### dontSeeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->dontSeeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### fillField
Fills a text field or textarea with the given string.
```
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], '[email protected]');
?>
```
* `param` $field
* `param` $value
### followRedirect
Follow pending redirect if there is one.
```
<?php
$I->followRedirect();
```
### grabAttributeFrom
Grabs the value of the given attribute value from the given element. Fails if element is not found.
```
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabCookie
Grabs a cookie value. You can set additional cookie params like `domain`, `path` in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try `$I->wait(0.1)`.
* `param` $cookie
* `param array` $params
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
```
<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param string` $uri optional
### grabMultiple
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
```
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return string[]`
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return string` Current page source code.
### grabServiceFromContainer
Grabs a service from a Laminas container. Recommended to use for unit testing.
```
<?php
$em = $I->grabServiceFromContainer('Doctrine\ORM\EntityManager');
```
* `[Part]` services
### grabTextFrom
Finds and returns the text contents of the given element. If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
```
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
* `param` $field
* `return array|mixed|null|string`
### haveHttpHeader
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
```
To use special chars in Header Key use HTML Character Entities: Example: Header with underscore - ‘Client\_Id’ should be represented as - ‘Client\_Id’ or ‘Client\_Id’
```
<?php
$I->haveHttpHeader('Client_Id', 'Codeception');
```
* `param string` $name the name of the request header
* `param string` $value the value to set it to for subsequent requests
### haveServerParameter
Sets SERVER parameter valid for all next requests.
```
$I->haveServerParameter('name', 'value');
```
* `param string` $name
* `param string` $value
### makeHtmlSnapshot
Use this method within an [interactive pause](../02-gettingstarted#Interactive-Pause) to save the HTML source code of the current page.
```
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
```
* `param null` $name
### moveBack
Moves back in history.
* `param int` $numberOfSteps (default value 1)
### resetCookie
Unsets cookie with the given name. You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.
```
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->see('strong')` will return true for strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
```
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set. You can set additional cookie params like `domain`, `path` as array passed in last argument.
```
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentRouteIs
Checks that current url matches route.
```
<?php
$I->seeCurrentRouteIs('posts.index');
$I->seeCurrentRouteIs('posts.show', ['id' => 8]));
```
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string. Unlike `seeInCurrentUrl`, this only matches the full URL.
```
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
```
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### seeElement
Checks that the given element exists on the page and is visible. You can also specify expected attributes of this element.
```
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
### seeInCurrentUrl
Checks that current URI contains the given string.
```
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### seeInField
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value. Fields are matched by label text, the “name” attribute, CSS, or XPath.
```
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
```
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
```
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
```
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there’s a link with the specified text. Give a full URL as the second parameter to match links with that exact URL.
```
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param string` $text
* `param string` $url optional
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
```
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected int or int[]
### seeOptionIsSelected
Checks that the given option is selected.
```
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### seePageNotFound
Asserts that current page has 404 response status code.
### seeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->seeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### seeResponseCodeIsBetween
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
* `param int` $from
* `param int` $to
### seeResponseCodeIsClientError
Checks that the response code is 4xx
### seeResponseCodeIsRedirection
Checks that the response code 3xx
### seeResponseCodeIsServerError
Checks that the response code is 5xx
### seeResponseCodeIsSuccessful
Checks that the response code 2xx
### selectOption
Selects an option in a select tag or in radio button group.
```
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
```
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
```
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### sendAjaxGetRequest
Sends an ajax GET request with the passed parameters. See `sendAjaxPostRequest()`
* `param` $uri
* `param` $params
### sendAjaxPostRequest
Sends an ajax POST request with the passed parameters. The appropriate HTTP header is added automatically: `X-Requested-With: XMLHttpRequest` Example:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['task' => 'lorem ipsum']);
```
Some frameworks (e.g. Symfony) create field names in the form of an “array”: `<input type="text" name="form[task]">` In this case you need to pass the fields like this:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['form' => [
'task' => 'lorem ipsum',
'category' => 'miscellaneous',
]]);
```
* `param string` $uri
* `param array` $params
### sendAjaxRequest
Sends an ajax request, using the passed HTTP method. See `sendAjaxPostRequest()` Example:
```
<?php
$I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
```
* `param` $method
* `param` $uri
* `param array` $params
### setCookie
Sets a cookie with the given name and value. You can set additional cookie params like `domain`, `path`, `expires`, `secure` in array passed as last argument.
```
<?php
$I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
?>
```
* `param` $name
* `param` $val
* `param array` $params
### setMaxRedirects
Sets the maximum number of redirects that the Client can follow.
```
<?php
$I->setMaxRedirects(2);
```
* `param int` $maxRedirects
### setServerParameters
Sets SERVER parameters valid for all next requests. this will remove old ones.
```
$I->setServerParameters([]);
```
### startFollowingRedirects
Enables automatic redirects to be followed by the client.
```
<?php
$I->startFollowingRedirects();
```
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client.
```
<?php
$I->stopFollowingRedirects();
```
### submitForm
Submits the given form on the page, with the given form values. Pass the form field’s values as an array in the second parameter.
Although this function can be used as a short-hand version of `fillField()`, `selectOption()`, `click()` etc. it has some important differences:
* Only field *names* may be used, not CSS/XPath selectors nor field labels
* If a field is sent to this function that does *not* exist on the page, it will silently be added to the HTTP request. This is helpful for testing some types of forms, but be aware that you will *not* get an exception like you would if you called `fillField()` or `selectOption()` with a missing field.
Fields that are not provided will be filled by their values from the page, or from any previous calls to `fillField()`, `selectOption()` etc. You don’t need to click the ‘Submit’ button afterwards. This command itself triggers the request to form’s action.
You can optionally specify which button’s value to include in the request with the last parameter (as an alternative to explicitly setting its value in the second parameter), as button values are not otherwise included in the request.
Examples:
```
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample “Sign Up” form:
```
<form id="userForm">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Subscribe to our newsletter?
<input type="checkbox" name="user[newsletter]" value="1" checked="checked" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
],
'submitButton'
);
```
Note that “2” will be the submitted value for the “plan” field, as it is the selected option.
To uncheck the pre-checked checkbox “newsletter”, call `$I->uncheckOption(['name' => 'user[newsletter]']);` *before*, then submit the form as shown here (i.e. without the “newsletter” field in the `$params` array).
You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
]
);
```
This function works well when paired with `seeInFormFields()` for quickly testing CRUD interfaces and form validation logic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);
```
Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean `true`/`false` which will be replaced by the checkbox’s value in the DOM.
```
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false
],
'multiselect' => [
'first option value',
'second option value'
]
]);
```
Mixing string and boolean values for a checkbox’s value is not supported and may produce unexpected results.
Field names ending in `[]` must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:
```
<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```
<?php
// This way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
* `param` $selector
* `param` $params
* `param` $button
### switchToIframe
Switch to iframe or frame on the page.
Example:
```
<iframe name="another_frame" src="http://example.com">
```
```
<?php
# switch to iframe
$I->switchToIframe("another_frame");
```
* `param string` $name
### uncheckOption
Unticks a checkbox.
```
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
| programming_docs |
codeception Doctrine2 Doctrine2
=========
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-doctrine2
```
Alternatively, you can enable `Doctrine2` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Access the database using [Doctrine2 ORM](http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/).
When used with Symfony or Zend Framework 2, Doctrine’s Entity Manager is automatically retrieved from Service Locator. Set up your `functional.suite.yml` like this:
```
modules:
enabled:
- Symfony # 'ZF2' or 'Symfony'
- Doctrine2:
depends: Symfony
cleanup: true # All doctrine queries will be wrapped in a transaction, which will be rolled back at the end of each test
```
If you don’t use Symfony or Zend Framework, you need to specify a callback function to retrieve the Entity Manager:
```
modules:
enabled:
- Doctrine2:
connection_callback: ['MyDb', 'createEntityManager'] # Call the static method `MyDb::createEntityManager()` to get the Entity Manager
```
By default, the module will wrap everything into a transaction for each test and roll it back afterwards (this is controlled by the `cleanup` setting). By doing this, tests will run much faster and will be isolated from each other.
To use the Doctrine2 Module in acceptance tests, set up your `acceptance.suite.yml` like this:
```
modules:
enabled:
- Symfony:
part: SERVICES
- Doctrine2:
depends: Symfony
```
You cannot use `cleanup: true` in an acceptance test, since Codeception and your app (i.e. browser) are using two different connections to the database, so Codeception can’t wrap changes made by the app into a transaction.
Change purge mode of doctrine fixtures:
```
modules:
enabled:
- Doctrine2:
purge_mode: 1 //1 - DELETE, 2 - TRUNCATE, default DELETE
```
Status
------
* Maintainer: **davert**
* Stability: **stable**
* Contact: [email protected]
Config
------
Public Properties
-----------------
* `em` - Entity Manager
Note on parameters
------------------
Every method that expects some parameters to be checked against values in the database (`see...()`, `dontSee...()`, `grab...()`) can accept instance of [\Doctrine\Common\Collections\Criteria](https://www.doctrine-project.org/api/collections/latest/Doctrine/Common/Collections/Criteria.html) for more flexibility, e.g.:
```
$I->seeInRepository(User::class, [
'name' => 'John',
Criteria::create()->where(
Criteria::expr()->endsWith('email', '@domain.com')
),
]);
```
If criteria is just a `->where(...)` construct, you can pass just expression without criteria wrapper:
```
$I->seeInRepository(User::class, [
'name' => 'John',
Criteria::expr()->endsWith('email', '@domain.com'),
]);
```
Criteria can be used not only to filter data, but also to change the order of results:
```
$I->grabEntitiesFromRepository('User', [
'status' => 'active',
Criteria::create()->orderBy(['name' => 'asc']),
]);
```
Note that key is ignored, because actual field name is part of criteria and/or expression.
Actions
-------
### clearEntityManager
Performs $em->clear():
```
$I->clearEntityManager();
```
### dontSeeInRepository
Flushes changes to database and performs `findOneBy()` call for current repository.
* `param` $entity
* `param array` $params
### flushToDatabase
Performs $em->flush();
### grabEntitiesFromRepository
Selects entities from repository. It builds query based on array of parameters. You can use entity associations to build complex queries.
Example:
```
<?php
$users = $I->grabEntitiesFromRepository(User::class, ['name' => 'davert']);
?>
```
* `Available since` 1.1
* `param` $entity
* `param array` $params. For `IS NULL`, use `['field' => null]`
* `return array`
### grabEntityFromRepository
Selects a single entity from repository. It builds query based on array of parameters. You can use entity associations to build complex queries.
Example:
```
<?php
$user = $I->grabEntityFromRepository(User::class, ['id' => '1234']);
?>
```
* `Available since` 1.1
* `param` $entity
* `param array` $params. For `IS NULL`, use `['field' => null]`
* `return object`
### grabFromRepository
Selects field value from repository. It builds query based on array of parameters. You can use entity associations to build complex queries.
Example:
```
<?php
$email = $I->grabFromRepository(User::class, 'email', ['name' => 'davert']);
?>
```
* `Available since` 1.1
* `param` $entity
* `param` $field
* `param array` $params
### haveFakeRepository
Mocks the repository.
With this action you can redefine any method of any repository. Please, note: this fake repositories will be accessible through entity manager till the end of test.
Example:
```
<?php
$I->haveFakeRepository(User::class, ['findByUsername' => function($username) { return null; }]);
```
This creates a stub class for Entity\User repository with redefined method findByUsername, which will always return the NULL value.
* `param` $classname
* `param array` $methods
### haveInRepository
Persists a record into the repository. This method creates an entity, and sets its properties directly (via reflection). Setters of the entity won’t be executed, but you can create almost any entity and save it to the database. If the entity has a constructor, for optional parameters the default value will be used and for non-optional parameters the given fields (with a matching name) will be passed when calling the constructor before the properties get set directly (via reflection).
Returns the primary key of the newly created entity. The primary key value is extracted using Reflection API. If the primary key is composite, an array of values is returned.
```
$I->haveInRepository(User::class, ['name' => 'davert']);
```
This method also accepts instances as first argument, which is useful when the entity constructor has some arguments:
```
$I->haveInRepository(new User($arg), ['name' => 'davert']);
```
Alternatively, constructor arguments can be passed by name. Given User constructor signature is `__constructor($arg)`, the example above could be rewritten like this:
```
$I->haveInRepository(User::class, ['arg' => $arg, 'name' => 'davert']);
```
If the entity has relations, they can be populated too. In case of [OneToMany](https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-bidirectional) the following format is expected:
```
$I->haveInRepository(User::class, [
'name' => 'davert',
'posts' => [
['title' => 'Post 1'],
['title' => 'Post 2'],
],
]);
```
For [ManyToOne](https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#many-to-one-unidirectional) the format is slightly different:
```
$I->haveInRepository(User::class, [
'name' => 'davert',
'post' => [
'title' => 'Post 1',
],
]);
```
This works recursively, so you can create deep structures in a single call.
Note that `$em->persist()`, `$em->refresh()`, and `$em->flush()` are called every time.
* `param string|object` $classNameOrInstance
* `param array` $data
### loadFixtures
Loads fixtures. Fixture can be specified as a fully qualified class name, an instance, or an array of class names/instances.
```
<?php
$I->loadFixtures(AppFixtures::class);
$I->loadFixtures([AppFixtures1::class, AppFixtures2::class]);
$I->loadFixtures(new AppFixtures);
```
By default fixtures are loaded in ‘append’ mode. To replace all data in database, use `false` as second parameter:
```
<?php
$I->loadFixtures(AppFixtures::class, false);
```
This method requires [`doctrine/data-fixtures`](https://github.com/doctrine/data-fixtures) to be installed.
* `param string|string[]|object[]` $fixtures
* `param bool` $append @throws ModuleException @throws ModuleRequireException
### onReconfigure
HOOK to be executed when config changes with `_reconfigure`.
### persistEntity
This method is deprecated in favor of `haveInRepository()`. Its functionality is exactly the same.
### refreshEntities
Performs $em->refresh() on every passed entity:
```
$I->refreshEntities($user);
$I->refreshEntities([$post1, $post2, $post3]]);
```
This can useful in acceptance tests where entity can become invalid due to external (relative to entity manager used in tests) changes.
* `param object|object[]` $entities
### seeInRepository
Flushes changes to database, and executes a query with parameters defined in an array. You can use entity associations to build complex queries.
Example:
```
<?php
$I->seeInRepository(User::class, ['name' => 'davert']);
$I->seeInRepository(User::class, ['name' => 'davert', 'Company' => ['name' => 'Codegyre']]);
$I->seeInRepository(Client::class, ['User' => ['Company' => ['name' => 'Codegyre']]]);
?>
```
Fails if record for given criteria can't be found,
* `param` $entity
* `param array` $params
codeception Codeception\Util\JsonType Codeception\Util\JsonType
=========================
JsonType matches JSON structures against templates. You can specify the type of fields in JSON or add additional validation rules.
JsonType is used by REST module in `seeResponseMatchesJsonType` and `dontSeeResponseMatchesJsonType` methods.
Usage example:
```
<?php
$jsonType = new JsonType(['name' => 'davert', 'id' => 1]);
$jsonType->matches([
'name' => 'string:!empty',
'id' => 'integer:>0|string:>0',
]); // => true
$jsonType->matches([
'id' => 'string',
]); // => `id: 1` is not of type string
?>
```
Class JsonType @package Codeception\Util
### \_\_construct()
*public* \_\_construct($jsonArray)
Creates instance of JsonType Pass an array or `\Codeception\Util\JsonArray` with data. If non-associative array is passed - the very first element of it will be used for matching.
* | | |
| --- | --- |
| `param` $jsonArray array | \Codeception\Util\JsonArray |
[See source](https://github.com/Codeception/module-rest/blob/master/src/Codeception/Util/JsonType.php#L43)
### addCustomFilter()
*public static* addCustomFilter($name, callable $callable)
Adds custom filter to JsonType list. You should specify a name and parameters of a filter.
Example:
```
<?php
JsonType::addCustomFilter('slug', function($value) {
return strpos(' ', $value) !== false;
});
// => use it as 'string:slug'
// add custom function to matcher with `len($val)` syntax
// parameter matching patterns should be valid regex and start with `/` char
JsonType::addCustomFilter('/len\((.*?)\)/', function($value, $len) {
return strlen($value) == $len;
});
// use it as 'string:len(5)'
?>
```
* `param` $name
* `param callable` $callable
[See source](https://github.com/Codeception/module-rest/blob/master/src/Codeception/Util/JsonType.php#L76)
### cleanCustomFilters()
*public static* cleanCustomFilters()
Removes all custom filters
[See source](https://github.com/Codeception/module-rest/blob/master/src/Codeception/Util/JsonType.php#L84)
### matches()
*public* matches(array $jsonType)
Checks data against passed JsonType. If matching fails function returns a string with a message describing failure. On success returns `true`.
* `param array` $jsonType
* | | |
| --- | --- |
| `return` bool | string |
[See source](https://github.com/Codeception/module-rest/blob/master/src/Codeception/Util/JsonType.php#L97)
codeception Shorthand Functions Shorthand Functions
===================
Shorthand functions can be used in your Codeception tests or helpers.
### codecept\_debug($data)
Prints information when running in debug mode. String, array, or object can be provided as argument.
### codecept\_output\_dir()
Returns absolute path to output directory (`tests/_output`)
### codecept\_root\_dir()
Returns absolute path to the root directory (where `codeception.yml` is located)
### codecept\_data\_dir()
Returns absolute path to data directory (`tests/_data`)
codeception Codeception\Util\Locator Codeception\Util\Locator
========================
Set of useful functions for using CSS and XPath locators. Please check them before writing complex functional or acceptance tests.
### combine()
*public static* combine($selector1, $selector2)
Applies OR operator to any number of CSS or XPath selectors. You can mix up CSS and XPath selectors here.
```
<?php
use \Codeception\Util\Locator;
$I->see('Title', Locator::combine('h1','h2','h3'));
?>
```
This will search for `Title` text in either `h1`, `h2`, or `h3` tag. You can also combine CSS selector with XPath locator:
```
<?php
use \Codeception\Util\Locator;
$I->fillField(Locator::combine('form input[type=text]','//form/textarea[2]'), 'qwerty');
?>
```
As a result the Locator will produce a mixed XPath value that will be used in fillField action.
* `static`
* `param` $selector1
* `param` $selector2
* `throws` \Exception
* `return` string
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L50)
### contains()
*public static* contains($element, $text)
Locates an element containing a text inside. Either CSS or XPath locator can be passed, however they will be converted to XPath.
```
<?php
use Codeception\Util\Locator;
Locator::contains('label', 'Name'); // label containing name
Locator::contains('div[@contenteditable=true]', 'hello world');
```
* `param` $element
* `param` $text
* `return` string
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L292)
### elementAt()
*public static* elementAt($element, $position)
Locates element at position. Either CSS or XPath locator can be passed as locator, position is an integer. If a negative value is provided, counting starts from the last element. First element has index 1
```
<?php
use Codeception\Util\Locator;
Locator::elementAt('//table/tr', 2); // second row
Locator::elementAt('//table/tr', -1); // last row
Locator::elementAt('table#grind>tr', -2); // previous than last row
```
* `param string` $element CSS or XPath locator
* `param int` $position xpath index
* `return` mixed
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L318)
### find()
*public static* find($element, array $attributes)
Finds element by it’s attribute(s)
```
<?php
use \Codeception\Util\Locator;
$I->seeElement(Locator::find('img', ['title' => 'diagram']));
```
* `static`
* `param` $element
* `param` $attributes
* `return` string
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L159)
### firstElement()
*public static* firstElement($element)
Locates first element of group elements. Either CSS or XPath locator can be passed as locator, Equal to `Locator::elementAt($locator, 1)`
```
<?php
use Codeception\Util\Locator;
Locator::firstElement('//table/tr');
```
* `param` $element
* `return` mixed
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L348)
### href()
*public static* href($url)
Matches the *a* element with given URL
```
<?php
use \Codeception\Util\Locator;
$I->see('Log In', Locator::href('/login.php'));
?>
```
* `static`
* `param` $url
* `return` string
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L79)
### humanReadableString()
*public static* humanReadableString($selector)
Transforms strict locator, \Facebook\WebDriver\WebDriverBy into a string represenation
* `param` $selector
* `return` string
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L381)
### isCSS()
*public static* isCSS($selector)
Checks that provided string is CSS selector
```
<?php
Locator::isCSS('#user .hello') => true
Locator::isCSS('body') => true
Locator::isCSS('//body/p/user') => false
```
* `param` $selector
* `return` bool
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L186)
### isClass()
*public static* isClass($class)
Checks that a string is valid CSS class
```
<?php
Locator::isClass('.hello') => true
Locator::isClass('body') => false
Locator::isClass('//body/p/user') => false
```
* `param` $class
* `return` bool
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L270)
### isID()
*public static* isID($id)
Checks that a string is valid CSS ID
```
<?php
Locator::isID('#user') => true
Locator::isID('body') => false
Locator::isID('//body/p/user') => false
```
* `param` $id
* `return` bool
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L252)
### isPrecise()
*public static* isPrecise($locator)
* `param` $locator
* `return` bool
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L221)
### isXPath()
*public static* isXPath($locator)
Checks that locator is an XPath
```
<?php
Locator::isXPath('#user .hello') => false
Locator::isXPath('body') => false
Locator::isXPath('//body/p/user') => true
```
* `param` $locator
* `return` bool
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L210)
### lastElement()
*public static* lastElement($element)
Locates last element of group elements. Either CSS or XPath locator can be passed as locator, Equal to `Locator::elementAt($locator, -1)`
```
<?php
use Codeception\Util\Locator;
Locator::lastElement('//table/tr');
```
* `param` $element
* `return` mixed
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L369)
### option()
*public static* option($value)
Matches option by text:
```
<?php
use Codeception\Util\Locator;
$I->seeElement(Locator::option('Male'), '#select-gender');
```
* `param` $value
* `return` string
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L124)
### tabIndex()
*public static* tabIndex($index)
Matches the element with given tab index
Do you often use the `TAB` key to navigate through the web page? How do your site respond to this navigation? You could try to match elements by their tab position using `tabIndex` method of `Locator` class.
```
<?php
use \Codeception\Util\Locator;
$I->fillField(Locator::tabIndex(1), 'davert');
$I->fillField(Locator::tabIndex(2) , 'qwerty');
$I->click('Login');
?>
```
* `static`
* `param` $index
* `return` string
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Locator.php#L105)
codeception Codeception\Stub Codeception\Stub
================
###
*public static* make($class, $params = null, $testCase = null)
Instantiates a class without executing a constructor. Properties and methods can be set as a second parameter. Even protected and private properties can be set.
```
<?php
Stub::make('User');
Stub::make('User', ['name' => 'davert']);
?>
```
Accepts either name of class or object of that class
```
<?php
Stub::make(new User, ['name' => 'davert']);
?>
```
To replace method provide it’s name as a key in second parameter and it’s return value or callback function as parameter
```
<?php
Stub::make('User', ['save' => function () { return true; }]);
Stub::make('User', ['save' => true]);
?>
```
**To create a mock, pass current testcase name as last argument:**
```
<?php
Stub::make('User', [
'save' => \Codeception\Stub\Expected::once()
], $this);
```
* template RealInstanceType of object
* `param class-string<RealInstanceType>|RealInstanceType|callable(): class-string<RealInstanceType>` $class - A class to be mocked
* `param array` $params - properties and methods to set
* `param bool|\PHPUnit\Framework\TestCase` $testCase
* return \PHPUnit\Framework\MockObject\MockObject&RealInstanceType - mock
* throws \RuntimeException when class does not exist
* throws \Exception
###
*public static* factory($class, $num = null, $params = null)
Creates $num instances of class through `Stub::make`.
* `param mixed` $class
* `param int` $num
* `param array` $params
* return array
* throws \Exception
###
*public static* makeEmptyExcept($class, $method, $params = null, $testCase = null)
Instantiates class having all methods replaced with dummies except one. Constructor is not triggered. Properties and methods can be replaced. Even protected and private properties can be set.
```
<?php
Stub::makeEmptyExcept('User', 'save');
Stub::makeEmptyExcept('User', 'save', ['name' => 'davert']);
?>
```
Accepts either name of class or object of that class
```
<?php
* Stub::makeEmptyExcept(new User, 'save');
?>
```
To replace method provide it’s name as a key in second parameter and it’s return value or callback function as parameter
```
<?php
Stub::makeEmptyExcept('User', 'save', ['isValid' => function () { return true; }]);
Stub::makeEmptyExcept('User', 'save', ['isValid' => true]);
?>
```
**To create a mock, pass current testcase name as last argument:**
```
<?php
Stub::makeEmptyExcept('User', 'validate', [
'save' => \Codeception\Stub\Expected::once()
], $this);
```
* template
* `param class-string<RealInstanceType>|RealInstanceType|callable(): class-string<RealInstanceType>` $class - A class to be mocked
* `param string` $method
* `param array` $params
* `param bool|\PHPUnit\Framework\TestCase` $testCase
* return \PHPUnit\Framework\MockObject\MockObject&RealInstanceType
* throws \Exception
###
*public static* makeEmpty($class, $params = null, $testCase = null)
Instantiates class having all methods replaced with dummies. Constructor is not triggered. Properties and methods can be set as a second parameter. Even protected and private properties can be set.
```
<?php
Stub::makeEmpty('User');
Stub::makeEmpty('User', ['name' => 'davert']);
```
Accepts either name of class or object of that class
```
<?php
Stub::makeEmpty(new User, ['name' => 'davert']);
```
To replace method provide it’s name as a key in second parameter and it’s return value or callback function as parameter
```
<?php
Stub::makeEmpty('User', ['save' => function () { return true; }]);
Stub::makeEmpty('User', ['save' => true]);
```
**To create a mock, pass current testcase name as last argument:**
```
<?php
Stub::makeEmpty('User', [
'save' => \Codeception\Stub\Expected::once()
], $this);
```
* template RealInstanceType of object
* `param class-string<RealInstanceType>|RealInstanceType|callable(): class-string<RealInstanceType>` $class - A class to be mocked
* `param array` $params
* `param bool|\PHPUnit\Framework\TestCase` $testCase
* return \PHPUnit\Framework\MockObject\MockObject&RealInstanceType
* throws \Exception
###
*public static* copy($obj, $params = null)
Clones an object and redefines it’s properties (even protected and private)
* `param` $obj
* `param array` $params
* return mixed
* throws \Exception
###
*public static* construct($class, $constructorParams = null, $params = null, $testCase = null)
Instantiates a class instance by running constructor. Parameters for constructor passed as second argument Properties and methods can be set in third argument. Even protected and private properties can be set.
```
<?php
Stub::construct('User', ['autosave' => false]);
Stub::construct('User', ['autosave' => false], ['name' => 'davert']);
?>
```
Accepts either name of class or object of that class
```
<?php
Stub::construct(new User, ['autosave' => false], ['name' => 'davert']);
?>
```
To replace method provide it’s name as a key in third parameter and it’s return value or callback function as parameter
```
<?php
Stub::construct('User', [], ['save' => function () { return true; }]);
Stub::construct('User', [], ['save' => true]);
?>
```
**To create a mock, pass current testcase name as last argument:**
```
<?php
Stub::construct('User', [], [
'save' => \Codeception\Stub\Expected::once()
], $this);
```
* template RealInstanceType of object
* `param class-string<RealInstanceType>|RealInstanceType|callable(): class-string<RealInstanceType>` $class - A class to be mocked
* `param array` $constructorParams
* `param array` $params
* `param bool|\PHPUnit\Framework\TestCase` $testCase
* return \PHPUnit\Framework\MockObject\MockObject&RealInstanceType
* throws \Exception
###
*public static* constructEmpty($class, $constructorParams = null, $params = null, $testCase = null)
Instantiates a class instance by running constructor with all methods replaced with dummies. Parameters for constructor passed as second argument Properties and methods can be set in third argument. Even protected and private properties can be set.
```
<?php
Stub::constructEmpty('User', ['autosave' => false]);
Stub::constructEmpty('User', ['autosave' => false], ['name' => 'davert']);
```
Accepts either name of class or object of that class
```
<?php
Stub::constructEmpty(new User, ['autosave' => false], ['name' => 'davert']);
```
To replace method provide it’s name as a key in third parameter and it’s return value or callback function as parameter
```
<?php
Stub::constructEmpty('User', [], ['save' => function () { return true; }]);
Stub::constructEmpty('User', [], ['save' => true]);
```
**To create a mock, pass current testcase name as last argument:**
```
<?php
Stub::constructEmpty('User', [], [
'save' => \Codeception\Stub\Expected::once()
], $this);
```
* template RealInstanceType of object
* `param class-string<RealInstanceType>|RealInstanceType|callable(): class-string<RealInstanceType>` $class - A class to be mocked
* `param array` $constructorParams
* `param array` $params
* `param bool|\PHPUnit\Framework\TestCase` $testCase
* return \PHPUnit\Framework\MockObject\MockObject&RealInstanceType
###
*public static* constructEmptyExcept($class, $method, $constructorParams = null, $params = null, $testCase = null)
Instantiates a class instance by running constructor with all methods replaced with dummies, except one. Parameters for constructor passed as second argument Properties and methods can be set in third argument. Even protected and private properties can be set.
```
<?php
Stub::constructEmptyExcept('User', 'save');
Stub::constructEmptyExcept('User', 'save', ['autosave' => false], ['name' => 'davert']);
?>
```
Accepts either name of class or object of that class
```
<?php
Stub::constructEmptyExcept(new User, 'save', ['autosave' => false], ['name' => 'davert']);
?>
```
To replace method provide it’s name as a key in third parameter and it’s return value or callback function as parameter
```
<?php
Stub::constructEmptyExcept('User', 'save', [], ['save' => function () { return true; }]);
Stub::constructEmptyExcept('User', 'save', [], ['save' => true]);
?>
```
**To create a mock, pass current testcase name as last argument:**
```
<?php
Stub::constructEmptyExcept('User', 'save', [], [
'save' => \Codeception\Stub\Expected::once()
], $this);
```
* template RealInstanceType of object
* `param class-string<RealInstanceType>|RealInstanceType|callable(): class-string<RealInstanceType>` $class - A class to be mocked
* `param string` $method
* `param array` $constructorParams
* `param array` $params
* `param bool|\PHPUnit\Framework\TestCase` $testCase
* return \PHPUnit\Framework\MockObject\MockObject&RealInstanceType
###
*public static* update($mock, array $params)
Replaces properties of current stub
* `param \PHPUnit\Framework\MockObject\MockObject` $mock
* `param array` $params
* return mixed
* throws \LogicException
###
*public static* consecutive()
Stubbing a method call to return a list of values in the specified order.
```
<?php
$user = Stub::make('User', ['getName' => Stub::consecutive('david', 'emma', 'sam', 'amy')]);
$user->getName(); //david
$user->getName(); //emma
$user->getName(); //sam
$user->getName(); //amy
?>
```
* return ConsecutiveMap
| programming_docs |
codeception Codeception\Util\Fixtures Codeception\Util\Fixtures
=========================
Really basic class to store data in global array and use it in Cests/Tests.
```
<?php
Fixtures::add('user1', ['name' => 'davert']);
Fixtures::get('user1');
Fixtures::exists('user1');
?>
```
### add()
*public static* add($name, $data)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Fixtures.php#L21)
### cleanup()
*public static* cleanup($name = null)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Fixtures.php#L35)
### exists()
*public static* exists($name)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Fixtures.php#L45)
### get()
*public static* get($name)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Fixtures.php#L26)
codeception Codeception\Module Codeception\Module
==================
* *Uses* `Codeception\Util\Shared\Asserts`
Basic class for Modules and Helpers. You must extend from it while implementing own helpers.
Public methods of this class start with `_` prefix in order to ignore them in actor classes. Module contains **HOOKS** which allow to handle test execution routine.
### $includeInheritedActions
*public static* **$includeInheritedActions**
By setting it to false module wan’t inherit methods of parent class.
type `bool`
### $onlyActions
*public static* **$onlyActions**
Allows to explicitly set what methods have this class.
type `array`
### $excludeActions
*public static* **$excludeActions**
Allows to explicitly exclude actions from module.
type `array`
### $aliases
*public static* **$aliases**
Allows to rename actions
type `array`
### \_\_construct()
*public* \_\_construct($moduleContainer, $config = null)
Module constructor.
Requires module container (to provide access between modules of suite) and config.
* `param ModuleContainer` $moduleContainer
* `param array|null` $config
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L71)
### \_after()
*public* \_after($test)
**HOOK** executed after test
* `param TestInterface` $test
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L254)
### \_afterStep()
*public* \_afterStep($step)
**HOOK** executed after step
* `param Step` $step
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L236)
### \_afterSuite()
*public* \_afterSuite()
**HOOK** executed after suite
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L218)
### \_before()
*public* \_before($test)
**HOOK** executed before test
* `param TestInterface` $test
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L245)
### \_beforeStep()
*public* \_beforeStep($step)
**HOOK** executed before step
* `param Step` $step
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L227)
### \_beforeSuite()
*public* \_beforeSuite($settings = null)
**HOOK** executed before suite
* `param array` $settings
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L211)
### \_failed()
*public* \_failed($test, $fail)
**HOOK** executed when test fails but before `_after`
* `param TestInterface` $test
* `param \Exception` $fail
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L264)
### \_getConfig()
*public* \_getConfig($key = null)
Get config values or specific config item.
* `param mixed` $key
* `return` mixed the config item’s value or null if it doesn’t exist
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L351)
### \_getName()
*public* \_getName()
Returns a module name for a Module, a class name for Helper
* `return` string
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L178)
### \_hasRequiredFields()
*public* \_hasRequiredFields()
Checks if a module has required fields
* `return` bool
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L194)
### \_initialize()
*public* \_initialize()
**HOOK** triggered after module is created and configuration is loaded
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L202)
### \_reconfigure()
*public* \_reconfigure($config)
Allows to redefine config for a specific test. Config is restored at the end of a test.
```
<?php
// cleanup DB only for specific group of tests
public function _before(Test $test) {
if (in_array('cleanup', $test->getMetadata()->getGroups()) {
$this->getModule('Db')->_reconfigure(['cleanup' => true]);
}
}
```
* `param` $config
* `throws` Exception\ModuleConfigException
* `throws` ModuleException
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L120)
### \_resetConfig()
*public* \_resetConfig()
Reverts config changed by `_reconfigure`
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L138)
### \_setConfig()
*public* \_setConfig($config)
Allows to define initial module config. Can be used in `_beforeSuite` hook of Helpers or Extensions
```
<?php
public function _beforeSuite($settings = []) {
$this->getModule('otherModule')->_setConfig($this->myOtherConfig);
}
```
* `param` $config
* `throws` Exception\ModuleConfigException
* `throws` ModuleException
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L96)
### assert()
*protected* assert($arguments, $not = null)
* `param` $arguments
* `param bool` $not
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L17)
### assertArrayHasKey()
*protected* assertArrayHasKey($key, $array, $message = null)
Asserts that an array has a specified key.
* `param int|string` $key
* `param array|ArrayAccess` $array
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L21)
### assertArrayNotHasKey()
*protected* assertArrayNotHasKey($key, $array, $message = null)
Asserts that an array does not have a specified key.
* `param int|string` $key
* `param array|ArrayAccess` $array
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L33)
### assertClassHasAttribute()
*protected* assertClassHasAttribute($attributeName, $className, $message = null)
Asserts that a class has a specified attribute.
* `param string` $attributeName
* `param string` $className
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L45)
### assertClassHasStaticAttribute()
*protected* assertClassHasStaticAttribute($attributeName, $className, $message = null)
Asserts that a class has a specified static attribute.
* `param string` $attributeName
* `param string` $className
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L57)
### assertClassNotHasAttribute()
*protected* assertClassNotHasAttribute($attributeName, $className, $message = null)
Asserts that a class does not have a specified attribute.
* `param string` $attributeName
* `param string` $className
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L69)
### assertClassNotHasStaticAttribute()
*protected* assertClassNotHasStaticAttribute($attributeName, $className, $message = null)
Asserts that a class does not have a specified static attribute.
* `param string` $attributeName
* `param string` $className
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L81)
### assertContains()
*protected* assertContains($needle, $haystack, $message = null)
Asserts that a haystack contains a needle.
* `param` $needle
* `param` $haystack
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L93)
### assertContainsEquals()
*protected* assertContainsEquals($needle, $haystack, $message = null)
* `param` $needle
* `param` $haystack
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L103)
### assertContainsOnly()
*protected* assertContainsOnly($type, $haystack, $isNativeType = null, $message = null)
Asserts that a haystack contains only values of a given type.
* `param string` $type
* `param` $haystack
* `param bool|null` $isNativeType
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L116)
### assertContainsOnlyInstancesOf()
*protected* assertContainsOnlyInstancesOf($className, $haystack, $message = null)
Asserts that a haystack contains only instances of a given class name.
* `param string` $className
* `param` $haystack
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L128)
### assertCount()
*protected* assertCount($expectedCount, $haystack, $message = null)
Asserts the number of elements of an array, Countable or Traversable.
* `param int` $expectedCount
* `param Countable|iterable` $haystack
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L140)
### assertDirectoryDoesNotExist()
*protected* assertDirectoryDoesNotExist($directory, $message = null)
Asserts that a directory does not exist.
* `param string` $directory
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L151)
### assertDirectoryExists()
*protected* assertDirectoryExists($directory, $message = null)
Asserts that a directory exists.
* `param string` $directory
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L162)
### assertDirectoryIsNotReadable()
*protected* assertDirectoryIsNotReadable($directory, $message = null)
Asserts that a directory exists and is not readable.
* `param string` $directory
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L173)
### assertDirectoryIsNotWritable()
*protected* assertDirectoryIsNotWritable($directory, $message = null)
Asserts that a directory exists and is not writable.
* `param string` $directory
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L184)
### assertDirectoryIsReadable()
*protected* assertDirectoryIsReadable($directory, $message = null)
Asserts that a directory exists and is readable.
* `param string` $directory
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L195)
### assertDirectoryIsWritable()
*protected* assertDirectoryIsWritable($directory, $message = null)
Asserts that a directory exists and is writable.
* `param string` $directory
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L206)
### assertDoesNotMatchRegularExpression()
*protected* assertDoesNotMatchRegularExpression($pattern, $string, $message = null)
Asserts that a string does not match a given regular expression.
* `param string` $pattern
* `param string` $string
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L218)
### assertEmpty()
*protected* assertEmpty($actual, $message = null)
Asserts that a variable is empty.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L229)
### assertEquals()
*protected* assertEquals($expected, $actual, $message = null)
Asserts that two variables are equal.
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L241)
### assertEqualsCanonicalizing()
*protected* assertEqualsCanonicalizing($expected, $actual, $message = null)
Asserts that two variables are equal (canonicalizing).
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L253)
### assertEqualsIgnoringCase()
*protected* assertEqualsIgnoringCase($expected, $actual, $message = null)
Asserts that two variables are equal (ignoring case).
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L265)
### assertEqualsWithDelta()
*protected* assertEqualsWithDelta($expected, $actual, $delta, $message = null)
Asserts that two variables are equal (with delta).
* `param` $expected
* `param` $actual
* `param float` $delta
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L278)
### assertFalse()
*protected* assertFalse($condition, $message = null)
Asserts that a condition is false.
* `param` $condition
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L289)
### assertFileDoesNotExist()
*protected* assertFileDoesNotExist($filename, $message = null)
Asserts that a file does not exist.
* `param string` $filename
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L300)
### assertFileEquals()
*protected* assertFileEquals($expected, $actual, $message = null)
Asserts that the contents of one file is equal to the contents of another file.
* `param string` $expected
* `param string` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L312)
### assertFileEqualsCanonicalizing()
*protected* assertFileEqualsCanonicalizing($expected, $actual, $message = null)
Asserts that the contents of one file is equal to the contents of another file (canonicalizing).
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L324)
### assertFileEqualsIgnoringCase()
*protected* assertFileEqualsIgnoringCase($expected, $actual, $message = null)
Asserts that the contents of one file is equal to the contents of another file (ignoring case).
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L336)
### assertFileExists()
*protected* assertFileExists($filename, $message = null)
Asserts that a file exists.
* `param string` $filename
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L347)
### assertFileIsNotReadable()
*protected* assertFileIsNotReadable($file, $message = null)
Asserts that a file exists and is not readable.
* `param string` $file
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L358)
### assertFileIsNotWritable()
*protected* assertFileIsNotWritable($file, $message = null)
Asserts that a file exists and is not writable.
* `param string` $file
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L369)
### assertFileIsReadable()
*protected* assertFileIsReadable($file, $message = null)
Asserts that a file exists and is readable.
* `param string` $file
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L380)
### assertFileIsWritable()
*protected* assertFileIsWritable($file, $message = null)
Asserts that a file exists and is writable.
* `param string` $file
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L391)
### assertFileNotEquals()
*protected* assertFileNotEquals($expected, $actual, $message = null)
Asserts that the contents of one file is not equal to the contents of another file.
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L403)
### assertFileNotEqualsCanonicalizing()
*protected* assertFileNotEqualsCanonicalizing($expected, $actual, $message = null)
Asserts that the contents of one file is not equal to the contents of another file (canonicalizing).
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L415)
### assertFileNotEqualsIgnoringCase()
*protected* assertFileNotEqualsIgnoringCase($expected, $actual, $message = null)
Asserts that the contents of one file is not equal to the contents of another file (ignoring case).
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L427)
### assertFileNotExists()
*protected* assertFileNotExists($filename, $message = null)
Asserts that a file does not exist.
* `param string` $filename
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L44)
### assertFinite()
*protected* assertFinite($actual, $message = null)
Asserts that a variable is finite.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L438)
### assertGreaterOrEquals()
*protected* assertGreaterOrEquals($expected, $actual, $message = null)
Asserts that a value is greater than or equal to another value.
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L56)
### assertGreaterThan()
*protected* assertGreaterThan($expected, $actual, $message = null)
Asserts that a value is greater than another value.
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L450)
### assertGreaterThanOrEqual()
*protected* assertGreaterThanOrEqual($expected, $actual, $message = null)
Asserts that a value is greater than or equal to another value.
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L462)
### assertInfinite()
*protected* assertInfinite($actual, $message = null)
Asserts that a variable is infinite.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L473)
### assertInstanceOf()
*protected* assertInstanceOf($expected, $actual, $message = null)
Asserts that a variable is of a given type.
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L485)
### assertIsArray()
*protected* assertIsArray($actual, $message = null)
Asserts that a variable is of type array.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L496)
### assertIsBool()
*protected* assertIsBool($actual, $message = null)
Asserts that a variable is of type bool.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L507)
### assertIsCallable()
*protected* assertIsCallable($actual, $message = null)
Asserts that a variable is of type callable.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L518)
### assertIsClosedResource()
*protected* assertIsClosedResource($actual, $message = null)
Asserts that a variable is of type resource and is closed.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L529)
### assertIsEmpty()
*protected* assertIsEmpty($actual, $message = null)
Asserts that a variable is empty.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L67)
### assertIsFloat()
*protected* assertIsFloat($actual, $message = null)
Asserts that a variable is of type float.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L540)
### assertIsInt()
*protected* assertIsInt($actual, $message = null)
Asserts that a variable is of type int.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L551)
### assertIsIterable()
*protected* assertIsIterable($actual, $message = null)
Asserts that a variable is of type iterable.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L562)
### assertIsNotArray()
*protected* assertIsNotArray($actual, $message = null)
Asserts that a variable is not of type array.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L573)
### assertIsNotBool()
*protected* assertIsNotBool($actual, $message = null)
Asserts that a variable is not of type bool.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L584)
### assertIsNotCallable()
*protected* assertIsNotCallable($actual, $message = null)
Asserts that a variable is not of type callable.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L595)
### assertIsNotClosedResource()
*protected* assertIsNotClosedResource($actual, $message = null)
Asserts that a variable is not of type resource.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L606)
### assertIsNotFloat()
*protected* assertIsNotFloat($actual, $message = null)
Asserts that a variable is not of type float.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L617)
### assertIsNotInt()
*protected* assertIsNotInt($actual, $message = null)
Asserts that a variable is not of type int.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L628)
### assertIsNotIterable()
*protected* assertIsNotIterable($actual, $message = null)
Asserts that a variable is not of type iterable.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L639)
### assertIsNotNumeric()
*protected* assertIsNotNumeric($actual, $message = null)
Asserts that a variable is not of type numeric.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L650)
### assertIsNotObject()
*protected* assertIsNotObject($actual, $message = null)
Asserts that a variable is not of type object.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L661)
### assertIsNotReadable()
*protected* assertIsNotReadable($filename, $message = null)
Asserts that a file/dir exists and is not readable.
* `param string` $filename
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L672)
### assertIsNotResource()
*protected* assertIsNotResource($actual, $message = null)
Asserts that a variable is not of type resource.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L683)
### assertIsNotScalar()
*protected* assertIsNotScalar($actual, $message = null)
Asserts that a variable is not of type scalar.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L694)
### assertIsNotString()
*protected* assertIsNotString($actual, $message = null)
Asserts that a variable is not of type string.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L705)
### assertIsNotWritable()
*protected* assertIsNotWritable($filename, $message = null)
Asserts that a file/dir exists and is not writable.
* `param` $filename
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L716)
### assertIsNumeric()
*protected* assertIsNumeric($actual, $message = null)
Asserts that a variable is of type numeric.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L727)
### assertIsObject()
*protected* assertIsObject($actual, $message = null)
Asserts that a variable is of type object.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L738)
### assertIsReadable()
*protected* assertIsReadable($filename, $message = null)
Asserts that a file/dir is readable.
* `param` $filename
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L749)
### assertIsResource()
*protected* assertIsResource($actual, $message = null)
Asserts that a variable is of type resource.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L760)
### assertIsScalar()
*protected* assertIsScalar($actual, $message = null)
Asserts that a variable is of type scalar.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L771)
### assertIsString()
*protected* assertIsString($actual, $message = null)
Asserts that a variable is of type string.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L782)
### assertIsWritable()
*protected* assertIsWritable($filename, $message = null)
Asserts that a file/dir exists and is writable.
* `param` $filename
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L793)
### assertJson()
*protected* assertJson($actualJson, $message = null)
Asserts that a string is a valid JSON string.
* `param string` $actualJson
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L804)
### assertJsonFileEqualsJsonFile()
*protected* assertJsonFileEqualsJsonFile($expectedFile, $actualFile, $message = null)
Asserts that two JSON files are equal.
* `param string` $expectedFile
* `param string` $actualFile
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L816)
### assertJsonFileNotEqualsJsonFile()
*protected* assertJsonFileNotEqualsJsonFile($expectedFile, $actualFile, $message = null)
Asserts that two JSON files are not equal.
* `param string` $expectedFile
* `param string` $actualFile
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L828)
### assertJsonStringEqualsJsonFile()
*protected* assertJsonStringEqualsJsonFile($expectedFile, $actualJson, $message = null)
Asserts that the generated JSON encoded object and the content of the given file are equal.
* `param string` $expectedFile
* `param string` $actualJson
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L840)
### assertJsonStringEqualsJsonString()
*protected* assertJsonStringEqualsJsonString($expectedJson, $actualJson, $message = null)
Asserts that two given JSON encoded objects or arrays are equal.
* `param string` $expectedJson
* `param string` $actualJson
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L852)
### assertJsonStringNotEqualsJsonFile()
*protected* assertJsonStringNotEqualsJsonFile($expectedFile, $actualJson, $message = null)
Asserts that the generated JSON encoded object and the content of the given file are not equal.
* `param string` $expectedFile
* `param string` $actualJson
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L864)
### assertJsonStringNotEqualsJsonString()
*protected* assertJsonStringNotEqualsJsonString($expectedJson, $actualJson, $message = null)
Asserts that two given JSON encoded objects or arrays are not equal.
* `param string` $expectedJson
* `param string` $actualJson
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L876)
### assertLessOrEquals()
*protected* assertLessOrEquals($expected, $actual, $message = null)
Asserts that a value is smaller than or equal to another value.
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L79)
### assertLessThan()
*protected* assertLessThan($expected, $actual, $message = null)
Asserts that a value is smaller than another value.
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L888)
### assertLessThanOrEqual()
*protected* assertLessThanOrEqual($expected, $actual, $message = null)
Asserts that a value is smaller than or equal to another value.
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L900)
### assertMatchesRegularExpression()
*protected* assertMatchesRegularExpression($pattern, $string, $message = null)
Asserts that a string matches a given regular expression.
* `param string` $pattern
* `param string` $string
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L912)
### assertNan()
*protected* assertNan($actual, $message = null)
Asserts that a variable is nan.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L923)
### assertNot()
*protected* assertNot($arguments)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L33)
### assertNotContains()
*protected* assertNotContains($needle, $haystack, $message = null)
Asserts that a haystack does not contain a needle.
* `param` $needle
* `param` $haystack
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L935)
### assertNotContainsEquals()
*protected* assertNotContainsEquals($needle, $haystack, $message = null)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L940)
### assertNotContainsOnly()
*protected* assertNotContainsOnly($type, $haystack, $isNativeType = null, $message = null)
Asserts that a haystack does not contain only values of a given type.
* `param string` $type
* `param` $haystack
* `param bool|null` $isNativeType
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L953)
### assertNotCount()
*protected* assertNotCount($expectedCount, $haystack, $message = null)
Asserts the number of elements of an array, Countable or Traversable.
* `param int` $expectedCount
* `param Countable|iterable` $haystack
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L965)
### assertNotEmpty()
*protected* assertNotEmpty($actual, $message = null)
Asserts that a variable is not empty.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L976)
### assertNotEquals()
*protected* assertNotEquals($expected, $actual, $message = null)
Asserts that two variables are not equal.
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L988)
### assertNotEqualsCanonicalizing()
*protected* assertNotEqualsCanonicalizing($expected, $actual, $message = null)
Asserts that two variables are not equal (canonicalizing).
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1000)
### assertNotEqualsIgnoringCase()
*protected* assertNotEqualsIgnoringCase($expected, $actual, $message = null)
Asserts that two variables are not equal (ignoring case).
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1012)
### assertNotEqualsWithDelta()
*protected* assertNotEqualsWithDelta($expected, $actual, $delta, $message = null)
Asserts that two variables are not equal (with delta).
* `param` $expected
* `param` $actual
* `param float` $delta
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1025)
### assertNotFalse()
*protected* assertNotFalse($condition, $message = null)
Asserts that a condition is not false.
* `param` $condition
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1036)
### assertNotInstanceOf()
*protected* assertNotInstanceOf($expected, $actual, $message = null)
Asserts that a variable is not of a given type.
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1048)
### assertNotNull()
*protected* assertNotNull($actual, $message = null)
Asserts that a variable is not null.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1059)
### assertNotRegExp()
*protected* assertNotRegExp($pattern, $string, $message = null)
Asserts that a string does not match a given regular expression.
* `param string` $pattern
* `param string` $string
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L91)
### assertNotSame()
*protected* assertNotSame($expected, $actual, $message = null)
Asserts that two variables do not have the same type and value.
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1071)
### assertNotSameSize()
*protected* assertNotSameSize($expected, $actual, $message = null)
Assert that the size of two arrays (or `Countable` or `Traversable` objects) is not the same.
* `param Countable|iterable` $expected
* `param Countable|iterable` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1083)
### assertNotTrue()
*protected* assertNotTrue($condition, $message = null)
Asserts that a condition is not true.
* `param` $condition
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1094)
### assertNull()
*protected* assertNull($actual, $message = null)
Asserts that a variable is null.
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1105)
### assertObjectHasAttribute()
*protected* assertObjectHasAttribute($attributeName, $object, $message = null)
Asserts that an object has a specified attribute.
* `param string` $attributeName
* `param object` $object
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1117)
### assertObjectNotHasAttribute()
*protected* assertObjectNotHasAttribute($attributeName, $object, $message = null)
Asserts that an object does not have a specified attribute.
* `param string` $attributeName
* `param object` $object
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1129)
### assertRegExp()
*protected* assertRegExp($pattern, $string, $message = null)
Asserts that a string matches a given regular expression.
* `param string` $pattern
* `param string` $string
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L103)
### assertSame()
*protected* assertSame($expected, $actual, $message = null)
Asserts that two variables have the same type and value.
* `param` $expected
* `param` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1141)
### assertSameSize()
*protected* assertSameSize($expected, $actual, $message = null)
Assert that the size of two arrays (or `Countable` or `Traversable` objects) is the same.
* `param Countable|iterable` $expected
* `param Countable|iterable` $actual
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1153)
### assertStringContainsString()
*protected* assertStringContainsString($needle, $haystack, $message = null)
* `param string` $needle
* `param string` $haystack
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1163)
### assertStringContainsStringIgnoringCase()
*protected* assertStringContainsStringIgnoringCase($needle, $haystack, $message = null)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1168)
### assertStringEndsNotWith()
*protected* assertStringEndsNotWith($suffix, $string, $message = null)
Asserts that a string ends not with a given suffix.
* `param string` $suffix
* `param string` $string
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1180)
### assertStringEndsWith()
*protected* assertStringEndsWith($suffix, $string, $message = null)
Asserts that a string ends with a given suffix.
* `param string` $suffix
* `param string` $string
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1192)
### assertStringEqualsFile()
*protected* assertStringEqualsFile($expectedFile, $actualString, $message = null)
Asserts that the contents of a string is equal to the contents of a file.
* `param string` $expectedFile
* `param string` $actualString
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1204)
### assertStringEqualsFileCanonicalizing()
*protected* assertStringEqualsFileCanonicalizing($expectedFile, $actualString, $message = null)
Asserts that the contents of a string is equal to the contents of a file (canonicalizing).
* `param string` $expectedFile
* `param string` $actualString
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1216)
### assertStringEqualsFileIgnoringCase()
*protected* assertStringEqualsFileIgnoringCase($expectedFile, $actualString, $message = null)
Asserts that the contents of a string is equal to the contents of a file (ignoring case).
* `param string` $expectedFile
* `param string` $actualString
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1228)
### assertStringMatchesFormat()
*protected* assertStringMatchesFormat($format, $string, $message = null)
Asserts that a string matches a given format string.
* `param string` $format
* `param string` $string
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1240)
### assertStringMatchesFormatFile()
*protected* assertStringMatchesFormatFile($formatFile, $string, $message = null)
Asserts that a string matches a given format file.
* `param string` $formatFile
* `param string` $string
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1252)
### assertStringNotContainsString()
*protected* assertStringNotContainsString($needle, $haystack, $message = null)
* `param string` $needle
* `param string` $haystack
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1262)
### assertStringNotContainsStringIgnoringCase()
*protected* assertStringNotContainsStringIgnoringCase($needle, $haystack, $message = null)
* `param string` $needle
* `param string` $haystack
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1272)
### assertStringNotEqualsFile()
*protected* assertStringNotEqualsFile($expectedFile, $actualString, $message = null)
Asserts that the contents of a string is not equal to the contents of a file.
* `param string` $expectedFile
* `param string` $actualString
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1284)
### assertStringNotEqualsFileCanonicalizing()
*protected* assertStringNotEqualsFileCanonicalizing($expectedFile, $actualString, $message = null)
Asserts that the contents of a string is not equal to the contents of a file (canonicalizing).
* `param string` $expectedFile
* `param string` $actualString
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1295)
### assertStringNotEqualsFileIgnoringCase()
*protected* assertStringNotEqualsFileIgnoringCase($expectedFile, $actualString, $message = null)
Asserts that the contents of a string is not equal to the contents of a file (ignoring case).
* `param string` $expectedFile
* `param string` $actualString
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1307)
### assertStringNotMatchesFormat()
*protected* assertStringNotMatchesFormat($format, $string, $message = null)
Asserts that a string does not match a given format string.
* `param string` $format
* `param string` $string
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1319)
### assertStringNotMatchesFormatFile()
*protected* assertStringNotMatchesFormatFile($formatFile, $string, $message = null)
Asserts that a string does not match a given format string.
* `param string` $formatFile
* `param string` $string
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1331)
### assertStringStartsNotWith()
*protected* assertStringStartsNotWith($prefix, $string, $message = null)
Asserts that a string starts not with a given prefix.
* `param string` $prefix
* `param string` $string
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1343)
### assertStringStartsWith()
*protected* assertStringStartsWith($prefix, $string, $message = null)
Asserts that a string starts with a given prefix.
* `param string` $prefix
* `param string` $string
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1355)
### assertThat()
*protected* assertThat($value, $constraint, $message = null)
Evaluates a PHPUnit\Framework\Constraint matcher object.
* `param` $value
* `param Constraint` $constraint
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1367)
### assertThatItsNot()
*protected* assertThatItsNot($value, $constraint, $message = null)
Evaluates a PHPUnit\Framework\Constraint matcher object.
* `param` $value
* `param Constraint` $constraint
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L115)
### assertTrue()
*protected* assertTrue($condition, $message = null)
Asserts that a condition is true.
* `param` $condition
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1378)
### assertXmlFileEqualsXmlFile()
*protected* assertXmlFileEqualsXmlFile($expectedFile, $actualFile, $message = null)
Asserts that two XML files are equal.
* `param string` $expectedFile
* `param string` $actualFile
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1390)
### assertXmlFileNotEqualsXmlFile()
*protected* assertXmlFileNotEqualsXmlFile($expectedFile, $actualFile, $message = null)
Asserts that two XML files are not equal.
* `param string` $expectedFile
* `param string` $actualFile
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1402)
### assertXmlStringEqualsXmlFile()
*protected* assertXmlStringEqualsXmlFile($expectedFile, $actualXml, $message = null)
Asserts that two XML documents are equal.
* `param string` $expectedFile
* `param DOMDocument|string` $actualXml
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1414)
### assertXmlStringEqualsXmlString()
*protected* assertXmlStringEqualsXmlString($expectedXml, $actualXml, $message = null)
Asserts that two XML documents are equal.
* `param DOMDocument|string` $expectedXml
* `param DOMDocument|string` $actualXml
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1426)
### assertXmlStringNotEqualsXmlFile()
*protected* assertXmlStringNotEqualsXmlFile($expectedFile, $actualXml, $message = null)
Asserts that two XML documents are not equal.
* `param string` $expectedFile
* `param DOMDocument|string` $actualXml
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1438)
### assertXmlStringNotEqualsXmlString()
*protected* assertXmlStringNotEqualsXmlString($expectedXml, $actualXml, $message = null)
Asserts that two XML documents are not equal.
* `param DOMDocument|string` $expectedXml
* `param DOMDocument|string` $actualXml
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1450)
### debug()
*protected* debug($message)
Print debug message to the screen.
* `param` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L273)
### debugSection()
*protected* debugSection($title, $message)
Print debug message with a title
* `param` $title
* `param` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L284)
### fail()
*protected* fail($message = null)
Fails a test with the given message.
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1460)
### getModule()
*protected* getModule($name)
Get another module by its name:
```
<?php
$this->getModule('WebDriver')->_findElements('.items');
```
* `param` $name
* `return` Module
* `throws` ModuleException
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L337)
### getModules()
*protected* getModules()
Get all enabled modules
* `return` array
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L320)
### hasModule()
*protected* hasModule($name)
Checks that module is enabled.
* `param` $name
* `return` bool
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L310)
### markTestIncomplete()
*protected* markTestIncomplete($message = null)
Mark the test as incomplete.
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1470)
### markTestSkipped()
*protected* markTestSkipped($message = null)
Mark the test as skipped.
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L1480)
### onReconfigure()
*protected* onReconfigure()
HOOK to be executed when config changes with `_reconfigure`.
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L130)
### scalarizeArray()
*protected* scalarizeArray($array)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L362)
### shortenMessage()
*protected* shortenMessage($message, $chars = null)
Short text message to an amount of chars
* `param` $message
* `param` $chars
* `return` string
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L299)
### validateConfig()
*protected* validateConfig()
Validates current config for required fields and required packages.
* `throws` Exception\ModuleConfigException
* `throws` ModuleException
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Module.php#L149)
| programming_docs |
codeception Configuration Configuration
=============
Global Configuration
--------------------
Configuration file `codeception.yml` is generated by `codecept bootstrap` command. It has preconfigured settings you can change.
Here are global options you can change inside configuration:
* `actor_suffix: Tester`: changes suffix for Actor classes. This defines a rule to generate new test suites. If you change `Tester` to `Ninja`, and generate new `api` test suite, you will get `ApiNinja` actor class.
* `namespace`: set a namespace for tests. All new tests and support classes will be generated under that namespace. Allows to configure [multiple test setups for one runner](../08-customization#Namespaces).
* `include: []`: include additional Codeception configurations for [multiple applications setup](../08-customization#Namespaces).
* `paths` directories used by Codeception. Default values are:
```
paths:
# where the tests stored
tests: tests
# directory for fixture data
data: tests/_data
# directory for support code
support: tests/_support
# directory for output
output: tests/_output
# directory for environment configuration
envs: tests/_envs
```
* `settings`: provide additional options for test runner. They may dramatically change the way Codeception is executed. For instance, take a note of `shuffle` option which allows to randomize tests execution order and `lint` option that toggles parsing a test file (using `php -l`) before loading it.
```
settings:
# enable/disable syntax of test files before loading
# for php < 7 exec('php -l') is used
# disable if you need to speed up tests execution
lint: true
# randomize test order
shuffle: true
# by default it's false on Windows
# use [ANSICON](https://github.com/adoxa/ansicon) to colorize output.
colors: true
# Generate XML JUnit report using strict schema
# Avoid putting additional report fields like steps or scenario names to it
# Required for XML reports on Jenkins CI
strict_xml: false
# Tests (especially functional) can take a lot of memory
# We set a high limit for them by default.
memory_limit: 1024M
# This value controls whether PHPUnit attempts to backup global variables
# See https://phpunit.de/manual/current/en/appendixes.annotations.html#appendixes.annotations.backupGlobals
backup_globals: true
# PHPUnit can be strict about tests that do not test anything
# See https://phpunit.de/manual/current/en/risky-tests.html#risky-tests.useless-tests
report_useless_tests: false
# PHPUnit can be strict about output during tests.
# See https://phpunit.de/manual/current/en/risky-tests.html#risky-tests.output-during-test-execution
disallow_test_output: false
# PHPUnit can be strict about tests that manipulate global state.
# See https://phpunit.de/manual/current/en/risky-tests.html#risky-tests.global-state-manipulation
be_strict_about_changes_to_global_state: false
# Log the incomplete and skipped tests into junit report
# See https://phpunit.de/manual/current/en/appendixes.configuration.html
# Section logging > junit
log_incomplete_skipped: false
# Set the error_reporting level
# You can specify either a predefined constant or an integer value
# See https://www.php.net/manual/en/function.error-reporting.php
# See https://www.php.net/manual/en/errorfunc.constants.php
error_level: E_ALL & ~E_STRICT & ~E_DEPRECATED
```
* `modules`: allows to create shared module configuration for all included suites.
```
modules:
config:
Db:
dsn: ''
user: ''
password: ''
dump: tests/_data/dump.sql
```
* `extends`: allows you to specify a file (relative to the `codeception.yml` file) that holds some already pre-defined values. This can be used to always use the same configuration for modules or whatever.
* `extensions`: allows to enable and configure [Codeception extensions](../08-customization#Extension), [Group Objects](../08-customization#Group-Objects), and [Custom Commands](../08-customization#Custom-Commands).
* `reporters`: allows to [change default reporters](../08-customization#Custom-Reporters) of Codeception
* `coverage`: [CodeCoverage](../11-codecoverage#Configuration) settings.
* `params`: allows to pass [external parameters](../06-modulesandhelpers#Dynamic-Configuration-With-Params) into module configuration.
* `gherkin`: BDD-specific [Gherkin options](../07-bdd#Configuration).
* `bootstrap`: bootstrap script that will be executed before all suites. A script should be put into `tests` directory.
Suite Configuration
-------------------
Each generated suite have its own configuration inside directory set by `paths: tests:` configuration option in `codeception.yml`. Each suite configuration is named like `suitename.suite.yml`. It allows to enable and configure modules, and more.
* `actor`: name of the actor class for current suite.
* `modules`: list of enabled modules with their configuration.
```
modules:
# enabled modules and helpers
enabled:
# built-in modules are listed by their names
- PhpBrowser:
# module configuration
url: http://localhost
# this module is pre-configured in global config
- Db
# helper names are listed by their class names
# by convention their names start with \
- \Helper\Acceptance
# additional modules configuration
# can be used for modules which are not currently enabled
config:
WebDriver:
browser: firefox
# list of modules disabled for this suite
disabled:
- WebDriver
```
* `extends`: allows you to specify a file (relative to the `*.suite.yml` file) that holds some already pre-defined values. This can be used to always use the same configuration for modules or whatever.
* `namespace`: default namespace of actor, support classes and tests.
* `suite_namespace`: default namespace for new tests of this suite (ignores `namespace` option)
* `env`: override any configuration per [environment](../07-advancedusage#Environments).
* `groups`: [groups](../07-advancedusage#Groups) with the list of tests of for corresponding group.
* `formats`: [formats](../07-advancedusage#Formats) with the list of extra test format classes.
* `coverage`: per suite [CodeCoverage](../11-codecoverage#Configuration) settings.
* `gherkin`: per suite [BDD Gherkin](../07-bdd#Configuration) settings.
* `error_level`: [error level](../04-functionaltests#Error-Reporting) for runner in current suite. Can be specified for unit, integration, functional tests. Passes value to `error_reporting` function. Suite specific value will override the global value.
* `bootstrap`: bootstrap script that will be executed before current suites. A script should be put into suite directory.
Config Templates (dist)
-----------------------
To provide the same configuration template for your development team, you can create a `codeception.dist.yml` config file, which will be loaded before `codeception.yml`. The dist config provides shared options, while local `codeception.yml` files override them on a per-installation basis. Therefore, `codeception.yml` should be ignored by your VCS system.
Config templates can also be used for suite configuration, by creating a `suitename.suite.dist.yml` file.
Configuration loading order:
1. `codeception.dist.yml`
2. `codeception.yml`
3. `acceptance.suite.dist.yml`
4. `acceptance.suite.yml`
5. environment config
codeception Console Commands Console Commands
================
Run
---
Executes tests.
Usage:
* `codecept run acceptance`: run all acceptance tests
* `codecept run tests/acceptance/MyCest.php`: run only MyCest
* `codecept run acceptance MyCest`: same as above
* `codecept run acceptance MyCest:myTestInIt`: run one test from a Cest
* `codecept run acceptance checkout.feature`: run feature-file
* `codecept run acceptance -g slow`: run tests from *slow* group
* `codecept run unit,functional`: run only unit and functional suites
Verbosity modes:
* `codecept run -v`:
* `codecept run --steps`: print step-by-step execution
* `codecept run -vv`: print steps and debug information
* `codecept run --debug`: alias for `-vv`
* `codecept run -vvv`: print Codeception-internal debug information
Load config:
* `codecept run -c path/to/another/config`: from another dir
* `codecept run -c another_config.yml`: from another config file
Override config values:
* `codecept run -o "settings: shuffle: true"`: enable shuffle
* `codecept run -o "settings: lint: false"`: disable linting
* `codecept run -o "reporters: report: \Custom\Reporter" --report`: use custom reporter
Run with specific extension
* `codecept run --ext Recorder` run with Recorder extension enabled
* `codecept run --ext DotReporter` run with DotReporter printer
* `codecept run --ext "My\Custom\Extension"` run with an extension loaded by class name
Full reference:
```
Arguments:
suite suite to be tested
test test to be run
Options:
-o, --override=OVERRIDE Override config values (multiple values allowed)
--config (-c) Use custom path for config
--report Show output in compact style
--html Generate html with results (default: "report.html")
--xml Generate JUnit XML Log (default: "report.xml")
--phpunit-xml Generate PhpUnit XML Log (default: "phpunit-report.xml")
--no-redirect Do not redirect to Composer-installed version in vendor/codeception
--tap Generate Tap Log (default: "report.tap.log")
--json Generate Json Log (default: "report.json")
--colors Use colors in output
--no-colors Force no colors in output (useful to override config file)
--silent Only outputs suite names and final results. Almost the same as `--quiet`
--steps Show steps in output
--debug (-d) Alias for `-vv`
--bootstrap Execute bootstrap script before the test
--coverage Run with code coverage (default: "coverage.serialized")
--coverage-html Generate CodeCoverage HTML report in path (default: "coverage")
--coverage-xml Generate CodeCoverage XML report in file (default: "coverage.xml")
--coverage-text Generate CodeCoverage text report in file (default: "coverage.txt")
--coverage-phpunit Generate CodeCoverage PHPUnit report in file (default: "coverage-phpunit")
--coverage-cobertura Generate CodeCoverage Cobertura report in file (default: "coverage-cobertura")
--no-exit Don't finish with exit code
--group (-g) Groups of tests to be executed (multiple values allowed)
--skip (-s) Skip selected suites (multiple values allowed)
--skip-group (-x) Skip selected groups (multiple values allowed)
--env Run tests in selected environments. (multiple values allowed, environments can be merged with ',')
--fail-fast (-f) Stop after first failure
--no-rebuild Do not rebuild actor classes on start
--help (-h) Display this help message.
--quiet (-q) Do not output any message. Almost the same as `--silent`
--verbose (-v|vv|vvv) Increase the verbosity of messages: `v` for normal output, `vv` for steps and debug, `vvv` for Codeception-internal debug
--version (-V) Display this application version.
--ansi Force ANSI output.
--no-ansi Disable ANSI output.
--no-interaction (-n) Do not ask any interactive question.
--seed Use the given seed for shuffling tests
```
GenerateEnvironment
-------------------
Generates empty environment configuration file into envs dir:
* `codecept g:env firefox`
Required to have `envs` path to be specified in `codeception.yml`
Init
----
GenerateFeature
---------------
Generates Feature file (in Gherkin):
* `codecept generate:feature suite Login`
* `codecept g:feature suite subdir/subdir/login.feature`
* `codecept g:feature suite login.feature -c path/to/project`
GenerateCest
------------
Generates Cest (scenario-driven object-oriented test) file:
* `codecept generate:cest suite Login`
* `codecept g:cest suite subdir/subdir/testnameCest.php`
* `codecept g:cest suite LoginCest -c path/to/project`
* `codecept g:cest "App\Login"`
GenerateScenarios
-----------------
Generates user-friendly text scenarios from scenario-driven tests (Cest).
* `codecept g:scenarios acceptance` - for all acceptance tests
* `codecept g:scenarios acceptance --format html` - in html format
* `codecept g:scenarios acceptance --path doc` - generate scenarios to `doc` dir
GenerateHelper
--------------
Creates empty Helper class.
* `codecept g:helper MyHelper`
* `codecept g:helper "My\Helper"`
GenerateStepObject
------------------
Generates StepObject class. You will be asked for steps you want to implement.
* `codecept g:stepobject acceptance AdminSteps`
* `codecept g:stepobject acceptance UserSteps --silent` - skip action questions
Build
-----
Generates Actor classes (initially Guy classes) from suite configs. Starting from Codeception 2.0 actor classes are auto-generated. Use this command to generate them manually.
* `codecept build`
* `codecept build path/to/project`
GherkinSnippets
---------------
Generates code snippets for matched feature files in a suite. Code snippets are expected to be implemented in Actor or PageObjects
Usage:
* `codecept gherkin:snippets acceptance` - snippets from all feature of acceptance tests
* `codecept gherkin:snippets acceptance/feature/users` - snippets from `feature/users` dir of acceptance tests
* `codecept gherkin:snippets acceptance user_account.feature` - snippets from a single feature file
* `codecept gherkin:snippets acceptance/feature/users/user_accout.feature` - snippets from feature file in a dir
Bootstrap
---------
Creates default config, tests directory and sample suites for current project. Use this command to start building a test suite.
By default it will create 3 suites **acceptance**, **functional**, and **unit**.
* `codecept bootstrap` - creates `tests` dir and `codeception.yml` in current dir.
* `codecept bootstrap --empty` - creates `tests` dir without suites
* `codecept bootstrap --namespace Frontend` - creates tests, and use `Frontend` namespace for actor classes and helpers.
* `codecept bootstrap --actor Wizard` - sets actor as Wizard, to have `TestWizard` actor in tests.
* `codecept bootstrap path/to/the/project` - provide different path to a project, where tests should be placed
GenerateSnapshot
----------------
Generates Snapshot. Snapshot can be used to test dynamical data. If suite name is provided, an actor class will be included into placeholder
* `codecept g:snapshot UserEmails`
* `codecept g:snapshot Products`
* `codecept g:snapshot acceptance UserEmails`
CompletionFallback
------------------
GenerateGroup
-------------
Creates empty GroupObject - extension which handles all group events.
* `codecept g:group Admin`
DryRun
------
Shows step by step execution process for scenario driven tests without actually running them.
* `codecept dry-run acceptance`
* `codecept dry-run acceptance MyCest`
* `codecept dry-run acceptance checkout.feature`
* `codecept dry-run tests/acceptance/MyCest.php`
GherkinSteps
------------
Prints all steps from all Gherkin contexts for a specific suite
```
codecept gherkin:steps acceptance
```
ConfigValidate
--------------
Validates and prints Codeception config. Use it do debug Yaml configs
Check config:
* `codecept config`: check global config
* `codecept config unit`: check suite config
Load config:
* `codecept config:validate -c path/to/another/config`: from another dir
* `codecept config:validate -c another_config.yml`: from another config file
Check overriding config values (like in `run` command)
* `codecept config:validate -o "settings: shuffle: true"`: enable shuffle
* `codecept config:validate -o "settings: lint: false"`: disable linting
* `codecept config:validate -o "reporters: report: \Custom\Reporter" --report`: use custom reporter
GeneratePageObject
------------------
Generates PageObject. Can be generated either globally, or just for one suite. If PageObject is generated globally it will act as UIMap, without any logic in it.
* `codecept g:page Login`
* `codecept g:page Registration`
* `codecept g:page acceptance Login`
Clean
-----
Recursively cleans `output` directory and generated code.
* `codecept clean`
GenerateTest
------------
Generates skeleton for Unit Test that extends `Codeception\TestCase\Test`.
* `codecept g:test unit User`
* `codecept g:test unit "App\User"`
SelfUpdate
----------
Auto-updates phar archive from official site: ‘http://codeception.com/codecept.phar’ .
* `php codecept.phar self-update`
@author Franck Cassedanne [[email protected]](https://codeception.com/cdn-cgi/l/email-protection#284e5a49464b43684b495b5b4d4c4946464d064b4745)
Console
-------
Try to execute test commands in run-time. You may try commands before writing the test.
* `codecept console acceptance` - starts acceptance suite environment. If you use WebDriver you can manipulate browser with Codeception commands.
GenerateSuite
-------------
Create new test suite. Requires suite name and actor name
* ``
* `codecept g:suite api` -> api + ApiTester
* `codecept g:suite integration Code` -> integration + CodeTester
* `codecept g:suite frontend Front` -> frontend + FrontTester
GenerateCept
------------
@deprecated
codeception Codeception\Util\XmlBuilder Codeception\Util\XmlBuilder
===========================
That’s a pretty simple yet powerful class to build XML structures in jQuery-like style. With no XML line actually written! Uses DOM extension to manipulate XML data.
```
<?php
$xml = new \Codeception\Util\XmlBuilder();
$xml->users
->user
->val(1)
->email
->val('[email protected]')
->attr('valid','true')
->parent()
->cart
->attr('empty','false')
->items
->item
->val('useful item');
->parents('user')
->active
->val(1);
echo $xml;
```
This will produce this XML
```
<?xml version="1.0"?>
<users>
<user>
1
<email valid="true">[email protected]</email>
<cart empty="false">
<items>
<item>useful item</item>
</items>
</cart>
<active>1</active>
</user>
</users>
```
Usage
-----
Builder uses chained calls. So each call to builder returns a builder object. Except for `getDom` and `__toString` methods.
* `$xml->node` - create new xml node and go inside of it.
* `$xml->node->val('value')` - sets the inner value of node
* `$xml->attr('name','value')` - set the attribute of node
* `$xml->parent()` - go back to parent node.
* `$xml->parents('user')` - go back through all parents to `user` node.
Export:
* `$xml->getDom` - get a DOMDocument object
* `$xml->__toString` - get a string representation of XML.
[Source code](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Util/XmlBuilder.php)
### \_\_construct()
*public* \_\_construct()
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/XmlBuilder.php#L80)
### \_\_get()
*public* \_\_get($tag)
Appends child node
* `param` $tag
* `return` XmlBuilder
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/XmlBuilder.php#L93)
### \_\_toString()
*public* \_\_toString()
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/XmlBuilder.php#L165)
### attr()
*public* attr($attr, $val)
Sets attribute for current node
* `param` $attr
* `param` $val
* `return` XmlBuilder
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/XmlBuilder.php#L120)
### getDom()
*public* getDom()
* `return` \DOMDocument
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/XmlBuilder.php#L173)
### parent()
*public* parent()
Traverses to parent
* `return` XmlBuilder
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/XmlBuilder.php#L131)
### parents()
*public* parents($tag)
Traverses to parent with $name
* `param` $tag
* `return` XmlBuilder
* `throws` \Exception
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/XmlBuilder.php#L145)
### val()
*public* val($val)
* `param` $val
* `return` XmlBuilder
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/XmlBuilder.php#L106)
| programming_docs |
codeception Codeception\Util\HttpCode Codeception\Util\HttpCode
=========================
Class containing constants of HTTP Status Codes and method to print HTTP code with its description.
Usage:
```
<?php
use \Codeception\Util\HttpCode;
// using REST, PhpBrowser, or any Framework module
$I->seeResponseCodeIs(HttpCode::OK);
$I->dontSeeResponseCodeIs(HttpCode::NOT_FOUND);
```
### getDescription()
*public static* getDescription($code)
Returns string with HTTP code and its description
```
<?php
HttpCode::getDescription(200); // '200 (OK)'
HttpCode::getDescription(401); // '401 (Unauthorized)'
```
* `param int` $code
* | | |
| --- | --- |
| `return` int | string |
[See source](https://github.com/Codeception/lib-innerbrowser/blob/master/src/Codeception/Util/HttpCode.php#L353)
codeception Codeception\InitTemplate Codeception\InitTemplate
========================
* *Uses* `Codeception\Command\Shared\FileSystem`, `Codeception\Command\Shared\Style`
Codeception templates allow creating a customized setup and configuration for your project. An abstract class for installation template. Each init template should extend it and implement a `setup` method. Use it to build a custom setup class which can be started with `codecept init` command.
```
<?php
namespace Codeception\Template; // it is important to use this namespace so codecept init could locate this template
class CustomInstall extends \Codeception\InitTemplate
{
public function setup()
{
// implement this
}
}
```
This class provides various helper methods for building customized setup
### \_\_construct()
*public* \_\_construct($input, $output)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L66)
### addModulesToComposer()
*protected* addModulesToComposer($modules)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L260)
### addStyles()
*public* addStyles($output)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L9)
### ask()
*protected* ask($question, $answer = null)
```
<?php
// propose firefox as default browser
$this->ask('select the browser of your choice', 'firefox');
// propose firefox or chrome possible options
$this->ask('select the browser of your choice', ['firefox', 'chrome']);
// ask true/false question
$this->ask('do you want to proceed (y/n)', true);
```
* `param string` $question
* `param mixed` $answer
* | | |
| --- | --- |
| `return` mixed | string |
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L108)
### breakParts()
*protected* breakParts($class)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L6)
### checkInstalled()
*protected* checkInstalled($dir = null)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L218)
### completeSuffix()
*protected* completeSuffix($filename, $suffix)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L25)
### createActor()
*protected* createActor($name, $directory, $suiteConfig)
Create an Actor class and generate actions for it. Requires a suite config as array in 3rd parameter.
* `param` $name
* `param` $directory
* `param` $suiteConfig
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L233)
### createDirectoryFor()
*protected* createDirectoryFor($basePath, $className = null)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L10)
### createEmptyDirectory()
*protected* createEmptyDirectory($dir)
Create an empty directory and add a placeholder file into it
* `param` $dir
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L205)
### createFile()
*protected* createFile($filename, $contents, $force = null, $flags = null)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L46)
### createHelper()
*protected* createHelper($name, $directory)
Create a helper class inside a directory
* `param` $name
* `param` $directory
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L184)
### getNamespaceHeader()
*protected* getNamespaceHeader($class)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L25)
### getNamespaceString()
*protected* getNamespaceString($class)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L19)
### getNamespaces()
*protected* getNamespaces($class)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L34)
### getShortClassName()
*protected* getShortClassName($class)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L13)
### gitIgnore()
*protected* gitIgnore($path)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L211)
### initDir()
*public* initDir($workDir)
Change the directory where Codeception should be installed.
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L76)
### removeSuffix()
*protected* removeSuffix($classname, $suffix)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L40)
### say()
*protected* say($message = null)
Print a message to console.
```
<?php
$this->say('Welcome to Setup');
```
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L137)
### sayError()
*protected* sayError($message)
Print error message
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L155)
### sayInfo()
*protected* sayInfo($message)
Print info message
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L173)
### saySuccess()
*protected* saySuccess($message)
Print a successful message
* `param string` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L146)
### sayWarning()
*protected* sayWarning($message)
Print warning message
* `param` $message
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L164)
### setup()
*abstract public* setup()
Override this class to create customized setup.
* `return` mixed
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L89)
### updateComposerClassMap()
*private* updateComposerClassMap($vendorDir = null)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/InitTemplate.php#L336)
codeception Codeception\Util\Autoload Codeception\Util\Autoload
=========================
Autoloader, which is fully compatible with PSR-4, and can be used to autoload your `Helper`, `Page`, and `Step` classes.
### addNamespace()
*public static* addNamespace($prefix, $base\_dir, $prepend = null)
Adds a base directory for a namespace prefix.
Example:
```
<?php
// app\Codeception\UserHelper will be loaded from '/path/to/helpers/UserHelper.php'
Autoload::addNamespace('app\Codeception', '/path/to/helpers');
// LoginPage will be loaded from '/path/to/pageobjects/LoginPage.php'
Autoload::addNamespace('', '/path/to/pageobjects');
Autoload::addNamespace('app\Codeception', '/path/to/controllers');
?>
```
* `param string` $prefix The namespace prefix.
* `param string` $base\_dir A base directory for class files in the namespace.
* `param bool` $prepend If true, prepend the base directory to the stack instead of appending it; this causes it to be searched first rather than last.
* `return` void
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Autoload.php#L45)
### load()
*public static* load($class)
[See source](https://github.com/Codeception/Codeception/blob/4.1/src/Codeception/Util/Autoload.php#L72)
codeception Mocks Mocks
=====
Declare mocks inside `Codeception\Test\Unit` class. If you want to use mocks outside it, check the reference for [Codeception/Stub](https://github.com/Codeception/Stub) library.
###
*public* make($class, $params = null)
Instantiates a class without executing a constructor. Properties and methods can be set as a second parameter. Even protected and private properties can be set.
```
<?php
$this->make('User');
$this->make('User', ['name' => 'davert']);
?>
```
Accepts either name of class or object of that class
```
<?php
$this->make(new User, ['name' => 'davert']);
?>
```
To replace method provide it’s name as a key in second parameter and it’s return value or callback function as parameter
```
<?php
$this->make('User', ['save' => function () { return true; }]);
$this->make('User', ['save' => true]);
```
@template RealInstanceType of object
* `param class-string<RealInstanceType>|RealInstanceType|callable(): class-string<RealInstanceType>` $class - A class to be mocked
* `param array` $params - properties and methods to set
@return \PHPUnit\Framework\MockObject\MockObject&RealInstanceType - mock @throws \RuntimeException when class does not exist @throws \Exception
###
*public* makeEmpty($class, $params = null)
Instantiates class having all methods replaced with dummies. Constructor is not triggered. Properties and methods can be set as a second parameter. Even protected and private properties can be set.
```
<?php
$this->makeEmpty('User');
$this->makeEmpty('User', ['name' => 'davert']);
```
Accepts either name of class or object of that class
```
<?php
$this->makeEmpty(new User, ['name' => 'davert']);
```
To replace method provide it’s name as a key in second parameter and it’s return value or callback function as parameter
```
<?php
$this->makeEmpty('User', ['save' => function () { return true; }]);
$this->makeEmpty('User', ['save' => true));
```
@template RealInstanceType of object
* `param class-string<RealInstanceType>|RealInstanceType|callable(): class-string<RealInstanceType>` $class - A class to be mocked
* `param array` $params
* `param bool|\PHPUnit\Framework\TestCase` $testCase
@return \PHPUnit\Framework\MockObject\MockObject&RealInstanceType @throws \Exception
###
*public* makeEmptyExcept($class, $method, $params = null)
Instantiates class having all methods replaced with dummies except one. Constructor is not triggered. Properties and methods can be replaced. Even protected and private properties can be set.
```
<?php
$this->makeEmptyExcept('User', 'save');
$this->makeEmptyExcept('User', 'save', ['name' => 'davert']);
?>
```
Accepts either name of class or object of that class
```
<?php
* $this->makeEmptyExcept(new User, 'save');
?>
```
To replace method provide it’s name as a key in second parameter and it’s return value or callback function as parameter
```
<?php
$this->makeEmptyExcept('User', 'save', ['isValid' => function () { return true; }]);
$this->makeEmptyExcept('User', 'save', ['isValid' => true]);
```
@template RealInstanceType of object
* `param class-string<RealInstanceType>|RealInstanceType|callable(): class-string<RealInstanceType>` $class - A class to be mocked
* `param string` $method
* `param array` $params
@return \PHPUnit\Framework\MockObject\MockObject&RealInstanceType @throws \Exception
###
*public* construct($class, $constructorParams = null, $params = null)
Instantiates a class instance by running constructor. Parameters for constructor passed as second argument Properties and methods can be set in third argument. Even protected and private properties can be set.
```
<?php
$this->construct('User', ['autosave' => false]);
$this->construct('User', ['autosave' => false], ['name' => 'davert']);
?>
```
Accepts either name of class or object of that class
```
<?php
$this->construct(new User, ['autosave' => false), ['name' => 'davert']);
?>
```
To replace method provide it’s name as a key in third parameter and it’s return value or callback function as parameter
```
<?php
$this->construct('User', [], ['save' => function () { return true; }]);
$this->construct('User', [], ['save' => true]);
?>
```
@template RealInstanceType of object
* `param class-string<RealInstanceType>|RealInstanceType|callable(): class-string<RealInstanceType>` $class - A class to be mocked
* `param array` $constructorParams
* `param array` $params
* `param bool|\PHPUnit\Framework\TestCase` $testCase
@return \PHPUnit\Framework\MockObject\MockObject&RealInstanceType @throws \Exception
###
*public* constructEmpty($class, $constructorParams = null, $params = null)
Instantiates a class instance by running constructor with all methods replaced with dummies. Parameters for constructor passed as second argument Properties and methods can be set in third argument. Even protected and private properties can be set.
```
<?php
$this->constructEmpty('User', ['autosave' => false]);
$this->constructEmpty('User', ['autosave' => false), ['name' => 'davert']);
```
Accepts either name of class or object of that class
```
<?php
$this->constructEmpty(new User, ['autosave' => false], ['name' => 'davert']);
```
To replace method provide it’s name as a key in third parameter and it’s return value or callback function as parameter
```
<?php
$this->constructEmpty('User', array(), array('save' => function () { return true; }));
$this->constructEmpty('User', array(), array('save' => true));
```
**To create a mock, pass current testcase name as last argument:**
```
<?php
$this->constructEmpty('User', [], [
'save' => \Codeception\Stub\Expected::once()
]);
```
@template RealInstanceType of object
* `param class-string<RealInstanceType>|RealInstanceType|callable(): class-string<RealInstanceType>` $class - A class to be mocked
* `param array` $constructorParams
* `param array` $params
@return \PHPUnit\Framework\MockObject\MockObject&RealInstanceType
###
*public* constructEmptyExcept($class, $method, $constructorParams = null, $params = null)
Instantiates a class instance by running constructor with all methods replaced with dummies, except one. Parameters for constructor passed as second argument Properties and methods can be set in third argument. Even protected and private properties can be set.
```
<?php
$this->constructEmptyExcept('User', 'save');
$this->constructEmptyExcept('User', 'save', ['autosave' => false], ['name' => 'davert']);
?>
```
Accepts either name of class or object of that class
```
<?php
$this->constructEmptyExcept(new User, 'save', ['autosave' => false], ['name' => 'davert']);
?>
```
To replace method provide it’s name as a key in third parameter and it’s return value or callback function as parameter
```
<?php
$this->constructEmptyExcept('User', 'save', [], ['save' => function () { return true; }]);
$this->constructEmptyExcept('User', 'save', [], ['save' => true]);
?>
```
@template RealInstanceType of object
* `param class-string<RealInstanceType>|RealInstanceType|callable(): class-string<RealInstanceType>` $class - A class to be mocked
* `param string` $method
* `param array` $constructorParams
* `param array` $params
@return \PHPUnit\Framework\MockObject\MockObject&RealInstanceType
###
*public static* never($params = null)
Checks if a method never has been invoked
If method invoked, it will immediately throw an exception.
```
<?php
use \Codeception\Stub\Expected;
$user = $this->make('User', [
'getName' => Expected::never(),
'someMethod' => function() {}
]);
$user->someMethod();
?>
```
* `param mixed` $params @return StubMarshaler
###
*public static* once($params = null)
Checks if a method has been invoked exactly one time.
If the number is less or greater it will later be checked in verify() and also throw an exception.
```
<?php
use \Codeception\Stub\Expected;
$user = $this->make(
'User',
array(
'getName' => Expected::once('Davert'),
'someMethod' => function() {}
)
);
$userName = $user->getName();
$this->assertEquals('Davert', $userName);
?>
```
Alternatively, a function can be passed as parameter:
```
<?php
Expected::once(function() { return Faker::name(); });
```
* `param mixed` $params
@return StubMarshaler
###
*public static* atLeastOnce($params = null)
Checks if a method has been invoked at least one time.
If the number of invocations is 0 it will throw an exception in verify.
```
<?php
use \Codeception\Stub\Expected;
$user = $this->make(
'User',
array(
'getName' => Expected::atLeastOnce('Davert')),
'someMethod' => function() {}
)
);
$user->getName();
$userName = $user->getName();
$this->assertEquals('Davert', $userName);
?>
```
Alternatively, a function can be passed as parameter:
```
<?php
Expected::atLeastOnce(function() { return Faker::name(); });
```
* `param mixed` $params
@return StubMarshaler
###
*public static* exactly($count, $params = null)
Checks if a method has been invoked a certain amount of times. If the number of invocations exceeds the value it will immediately throw an exception, If the number is less it will later be checked in verify() and also throw an exception.
```
<?php
use \Codeception\Stub;
use \Codeception\Stub\Expected;
$user = $this->make(
'User',
array(
'getName' => Expected::exactly(3, 'Davert'),
'someMethod' => function() {}
)
);
$user->getName();
$user->getName();
$userName = $user->getName();
$this->assertEquals('Davert', $userName);
?>
```
Alternatively, a function can be passed as parameter:
```
<?php
Expected::exactly(function() { return Faker::name() });
```
* `param int` $count
* `param mixed` $params
@return StubMarshaler
kubectl GETTING STARTED **GETTING STARTED**
===================
This section contains the most basic commands for getting a workload running on your cluster.
* `run` will start running 1 or more instances of a container image on your cluster.
* `expose` will load balance traffic across the running instances, and can create a HA proxy for accessing the containers from outside the cluster.
Once your workloads are running, you can use the commands in the [WORKING WITH APPS](#-strong-working-with-apps-strong-) section to inspect them.
---
create
======
> Create a pod using the data in pod.json
>
>
```
kubectl create -f ./pod.json
```
> Create a pod based on the JSON passed into stdin
>
>
```
cat pod.json | kubectl create -f -
```
> Edit the data in registry.yaml in JSON then create the resource using the edited data
>
>
```
kubectl create -f registry.yaml --edit -o json
```
Create a resource from a file or from stdin.
JSON and YAML formats are accepted.
### Usage
`$ kubectl create -f FILENAME`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| edit | | false | Edit the API resource before creating |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files to use to create the resource |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| raw | | | Raw URI to POST to the server. Uses the transport specified by the kubeconfig file. |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
| windows-line-endings | | false | Only relevant if --edit=true. Defaults to the line ending native to your platform. |
---
*clusterrole*
-------------
> Create a cluster role named "pod-reader" that allows user to perform "get", "watch" and "list" on pods
>
>
```
kubectl create clusterrole pod-reader --verb=get,list,watch --resource=pods
```
> Create a cluster role named "pod-reader" with ResourceName specified
>
>
```
kubectl create clusterrole pod-reader --verb=get --resource=pods --resource-name=readablepod --resource-name=anotherpod
```
> Create a cluster role named "foo" with API Group specified
>
>
```
kubectl create clusterrole foo --verb=get,list,watch --resource=rs.apps
```
> Create a cluster role named "foo" with SubResource specified
>
>
```
kubectl create clusterrole foo --verb=get,list,watch --resource=pods,pods/status
```
> Create a cluster role name "foo" with NonResourceURL specified
>
>
```
kubectl create clusterrole "foo" --verb=get --non-resource-url=/logs/*
```
> Create a cluster role name "monitoring" with AggregationRule specified
>
>
```
kubectl create clusterrole monitoring --aggregation-rule="rbac.example.com/aggregate-to-monitoring=true"
```
Create a cluster role.
### Usage
`$ kubectl create clusterrole NAME --verb=verb --resource=resource.group [--resource-name=resourcename] [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| aggregation-rule | | | An aggregation label selector for combining ClusterRoles. |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| non-resource-url | | [] | A partial url that user should have access to. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| resource | | [] | Resource that the rule applies to |
| resource-name | | [] | Resource in the white list that the rule applies to, repeat this flag for multiple items |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
| verb | | [] | Verb that applies to the resources contained in the rule |
---
*clusterrolebinding*
--------------------
> Create a cluster role binding for user1, user2, and group1 using the cluster-admin cluster role
>
>
```
kubectl create clusterrolebinding cluster-admin --clusterrole=cluster-admin --user=user1 --user=user2 --group=group1
```
Create a cluster role binding for a particular cluster role.
### Usage
`$ kubectl create clusterrolebinding NAME --clusterrole=NAME [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| clusterrole | | | ClusterRole this ClusterRoleBinding should reference |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| group | | [] | Groups to bind to the clusterrole. The flag can be repeated to add multiple groups. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| serviceaccount | | [] | Service accounts to bind to the clusterrole, in the format <namespace>:<name>. The flag can be repeated to add multiple service accounts. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*configmap*
-----------
> Create a new config map named my-config based on folder bar
>
>
```
kubectl create configmap my-config --from-file=path/to/bar
```
> Create a new config map named my-config with specified keys instead of file basenames on disk
>
>
```
kubectl create configmap my-config --from-file=key1=/path/to/bar/file1.txt --from-file=key2=/path/to/bar/file2.txt
```
> Create a new config map named my-config with key1=config1 and key2=config2
>
>
```
kubectl create configmap my-config --from-literal=key1=config1 --from-literal=key2=config2
```
> Create a new config map named my-config from the key=value pairs in the file
>
>
```
kubectl create configmap my-config --from-file=path/to/bar
```
> Create a new config map named my-config from an env file
>
>
```
kubectl create configmap my-config --from-env-file=path/to/foo.env --from-env-file=path/to/bar.env
```
Create a config map based on a file, directory, or specified literal value.
A single config map may package one or more key/value pairs.
When creating a config map based on a file, the key will default to the basename of the file, and the value will default to the file content. If the basename is an invalid key, you may specify an alternate key.
When creating a config map based on a directory, each file whose basename is a valid key in the directory will be packaged into the config map. Any directory entries except regular files are ignored (e.g. subdirectories, symlinks, devices, pipes, etc).
### Usage
`$ kubectl create configmap NAME [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| append-hash | | false | Append a hash of the configmap to its name. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| from-env-file | | [] | Specify the path to a file to read lines of key=val pairs to create a configmap. |
| from-file | | [] | Key file can be specified using its file path, in which case file basename will be used as configmap key, or optionally with a key and file path, in which case the given key will be used. Specifying a directory will iterate each named file in the directory whose basename is a valid configmap key. |
| from-literal | | [] | Specify a key and literal value to insert in configmap (i.e. mykey=somevalue) |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*cronjob*
---------
> Create a cron job
>
>
```
kubectl create cronjob my-job --image=busybox --schedule="*/1 * * * *"
```
> Create a cron job with a command
>
>
```
kubectl create cronjob my-job --image=busybox --schedule="*/1 * * * *" -- date
```
Create a cron job with the specified name.
### Usage
`$ kubectl create cronjob NAME --image=image --schedule='0/5 * * * ?' -- [COMMAND] [args...]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| image | | | Image name to run. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| restart | | | job's restart policy. supported values: OnFailure, Never |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| schedule | | | A schedule in the Cron format the job should be run with. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*deployment*
------------
> Create a deployment named my-dep that runs the busybox image
>
>
```
kubectl create deployment my-dep --image=busybox
```
> Create a deployment with a command
>
>
```
kubectl create deployment my-dep --image=busybox -- date
```
> Create a deployment named my-dep that runs the nginx image with 3 replicas
>
>
```
kubectl create deployment my-dep --image=nginx --replicas=3
```
> Create a deployment named my-dep that runs the busybox image and expose port 5701
>
>
```
kubectl create deployment my-dep --image=busybox --port=5701
```
Create a deployment with the specified name.
### Usage
`$ kubectl create deployment NAME --image=image -- [COMMAND] [args...]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| image | | [] | Image names to run. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| port | | -1 | The port that this container exposes. |
| replicas | r | 1 | Number of replicas to create. Default is 1. |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*ingress*
---------
> Create a single ingress called 'simple' that directs requests to foo.com/bar to svc # svc1:8080 with a tls secret "my-cert"
>
>
```
kubectl create ingress simple --rule="foo.com/bar=svc1:8080,tls=my-cert"
```
> Create a catch all ingress of "/path" pointing to service svc:port and Ingress Class as "otheringress"
>
>
```
kubectl create ingress catch-all --class=otheringress --rule="/path=svc:port"
```
> Create an ingress with two annotations: ingress.annotation1 and ingress.annotations2
>
>
```
kubectl create ingress annotated --class=default --rule="foo.com/bar=svc:port" \ --annotation ingress.annotation1=foo \ --annotation ingress.annotation2=bla
```
> Create an ingress with the same host and multiple paths
>
>
```
kubectl create ingress multipath --class=default \ --rule="foo.com/=svc:port" \ --rule="foo.com/admin/=svcadmin:portadmin"
```
> Create an ingress with multiple hosts and the pathType as Prefix
>
>
```
kubectl create ingress ingress1 --class=default \ --rule="foo.com/path*=svc:8080" \ --rule="bar.com/admin*=svc2:http"
```
> Create an ingress with TLS enabled using the default ingress certificate and different path types
>
>
```
kubectl create ingress ingtls --class=default \ --rule="foo.com/=svc:https,tls" \ --rule="foo.com/path/subpath*=othersvc:8080"
```
> Create an ingress with TLS enabled using a specific secret and pathType as Prefix
>
>
```
kubectl create ingress ingsecret --class=default \ --rule="foo.com/*=svc:8080,tls=secret1"
```
> Create an ingress with a default backend
>
>
```
kubectl create ingress ingdefault --class=default \ --default-backend=defaultsvc:http \ --rule="foo.com/*=svc:8080,tls=secret1"
```
Create an ingress with the specified name.
### Usage
`$ kubectl create ingress NAME --rule=host/path=service:port[,tls[=secret]]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| annotation | | [] | Annotation to insert in the ingress object, in the format annotation=value |
| class | | | Ingress Class to be used |
| default-backend | | | Default service for backend, in format of svcname:port |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| rule | | [] | Rule in format host/path=service:port[,tls=secretname]. Paths containing the leading character '\*' are considered pathType=Prefix. tls argument is optional. |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*job*
-----
> Create a job
>
>
```
kubectl create job my-job --image=busybox
```
> Create a job with a command
>
>
```
kubectl create job my-job --image=busybox -- date
```
> Create a job from a cron job named "a-cronjob"
>
>
```
kubectl create job test-job --from=cronjob/a-cronjob
```
Create a job with the specified name.
### Usage
`$ kubectl create job NAME --image=image [--from=cronjob/name] -- [COMMAND] [args...]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| from | | | The name of the resource to create a Job from (only cronjob is supported). |
| image | | | Image name to run. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*namespace*
-----------
> Create a new namespace named my-namespace
>
>
```
kubectl create namespace my-namespace
```
Create a namespace with the specified name.
### Usage
`$ kubectl create namespace NAME [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*poddisruptionbudget*
---------------------
> Create a pod disruption budget named my-pdb that will select all pods with the app=rails label # and require at least one of them being available at any point in time
>
>
```
kubectl create poddisruptionbudget my-pdb --selector=app=rails --min-available=1
```
> Create a pod disruption budget named my-pdb that will select all pods with the app=nginx label # and require at least half of the pods selected to be available at any point in time
>
>
```
kubectl create pdb my-pdb --selector=app=nginx --min-available=50%
```
Create a pod disruption budget with the specified name, selector, and desired minimum available pods.
### Usage
`$ kubectl create poddisruptionbudget NAME --selector=SELECTOR --min-available=N [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| max-unavailable | | | The maximum number or percentage of unavailable pods this budget requires. |
| min-available | | | The minimum number or percentage of available pods this budget requires. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| selector | | | A label selector to use for this budget. Only equality-based selector requirements are supported. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*priorityclass*
---------------
> Create a priority class named high-priority
>
>
```
kubectl create priorityclass high-priority --value=1000 --description="high priority"
```
> Create a priority class named default-priority that is considered as the global default priority
>
>
```
kubectl create priorityclass default-priority --value=1000 --global-default=true --description="default priority"
```
> Create a priority class named high-priority that cannot preempt pods with lower priority
>
>
```
kubectl create priorityclass high-priority --value=1000 --description="high priority" --preemption-policy="Never"
```
Create a priority class with the specified name, value, globalDefault and description.
### Usage
`$ kubectl create priorityclass NAME --value=VALUE --global-default=BOOL [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| description | | | description is an arbitrary string that usually provides guidelines on when this priority class should be used. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| global-default | | false | global-default specifies whether this PriorityClass should be considered as the default priority. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| preemption-policy | | PreemptLowerPriority | preemption-policy is the policy for preempting pods with lower priority. |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
| value | | 0 | the value of this priority class. |
---
*quota*
-------
> Create a new resource quota named my-quota
>
>
```
kubectl create quota my-quota --hard=cpu=1,memory=1G,pods=2,services=3,replicationcontrollers=2,resourcequotas=1,secrets=5,persistentvolumeclaims=10
```
> Create a new resource quota named best-effort
>
>
```
kubectl create quota best-effort --hard=pods=100 --scopes=BestEffort
```
Create a resource quota with the specified name, hard limits, and optional scopes.
### Usage
`$ kubectl create quota NAME [--hard=key1=value1,key2=value2] [--scopes=Scope1,Scope2] [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| hard | | | A comma-delimited set of resource=quantity pairs that define a hard limit. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| scopes | | | A comma-delimited set of quota scopes that must all match each object tracked by the quota. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*role*
------
> Create a role named "pod-reader" that allows user to perform "get", "watch" and "list" on pods
>
>
```
kubectl create role pod-reader --verb=get --verb=list --verb=watch --resource=pods
```
> Create a role named "pod-reader" with ResourceName specified
>
>
```
kubectl create role pod-reader --verb=get --resource=pods --resource-name=readablepod --resource-name=anotherpod
```
> Create a role named "foo" with API Group specified
>
>
```
kubectl create role foo --verb=get,list,watch --resource=rs.apps
```
> Create a role named "foo" with SubResource specified
>
>
```
kubectl create role foo --verb=get,list,watch --resource=pods,pods/status
```
Create a role with single rule.
### Usage
`$ kubectl create role NAME --verb=verb --resource=resource.group/subresource [--resource-name=resourcename] [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| resource | | [] | Resource that the rule applies to |
| resource-name | | [] | Resource in the white list that the rule applies to, repeat this flag for multiple items |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
| verb | | [] | Verb that applies to the resources contained in the rule |
---
*rolebinding*
-------------
> Create a role binding for user1, user2, and group1 using the admin cluster role
>
>
```
kubectl create rolebinding admin --clusterrole=admin --user=user1 --user=user2 --group=group1
```
Create a role binding for a particular role or cluster role.
### Usage
`$ kubectl create rolebinding NAME --clusterrole=NAME|--role=NAME [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| clusterrole | | | ClusterRole this RoleBinding should reference |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| group | | [] | Groups to bind to the role. The flag can be repeated to add multiple groups. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| role | | | Role this RoleBinding should reference |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| serviceaccount | | [] | Service accounts to bind to the role, in the format <namespace>:<name>. The flag can be repeated to add multiple service accounts. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*secret*
--------
Create a secret using specified subcommand.
### Usage
`$ kubectl create secret`
---
*secret docker-registry*
------------------------
> If you don't already have a .dockercfg file, you can create a dockercfg secret directly by using:
>
>
```
kubectl create secret docker-registry my-secret --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL
```
> Create a new secret named my-secret from ~/.docker/config.json
>
>
```
kubectl create secret docker-registry my-secret --from-file=.dockerconfigjson=path/to/.docker/config.json
```
Create a new secret for use with Docker registries.
Dockercfg secrets are used to authenticate against Docker registries.
When using the Docker command line to push images, you can authenticate to a given registry by running: '$ docker login DOCKER\_REGISTRY\_SERVER --username=DOCKER\_USER --password=DOCKER\_PASSWORD --email=DOCKER\_EMAIL'.
That produces a ~/.dockercfg file that is used by subsequent 'docker push' and 'docker pull' commands to authenticate to the registry. The email address is optional.
When creating applications, you may have a Docker registry that requires authentication. In order for the nodes to pull images on your behalf, they must have the credentials. You can provide this information by creating a dockercfg secret and attaching it to your service account.
### Usage
`$ kubectl create docker-registry NAME --docker-username=user --docker-password=password --docker-email=email [--docker-server=string] [--from-file=[key=]source] [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| append-hash | | false | Append a hash of the secret to its name. |
| docker-email | | | Email for Docker registry |
| docker-password | | | Password for Docker registry authentication |
| docker-server | | <https://index.docker.io/v1/> | Server location for Docker registry |
| docker-username | | | Username for Docker registry authentication |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| from-file | | [] | Key files can be specified using their file path, in which case a default name will be given to them, or optionally with a name and file path, in which case the given name will be used. Specifying a directory will iterate each named file in the directory that is a valid secret key. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*secret generic*
----------------
> Create a new secret named my-secret with keys for each file in folder bar
>
>
```
kubectl create secret generic my-secret --from-file=path/to/bar
```
> Create a new secret named my-secret with specified keys instead of names on disk
>
>
```
kubectl create secret generic my-secret --from-file=ssh-privatekey=path/to/id_rsa --from-file=ssh-publickey=path/to/id_rsa.pub
```
> Create a new secret named my-secret with key1=supersecret and key2=topsecret
>
>
```
kubectl create secret generic my-secret --from-literal=key1=supersecret --from-literal=key2=topsecret
```
> Create a new secret named my-secret using a combination of a file and a literal
>
>
```
kubectl create secret generic my-secret --from-file=ssh-privatekey=path/to/id_rsa --from-literal=passphrase=topsecret
```
> Create a new secret named my-secret from env files
>
>
```
kubectl create secret generic my-secret --from-env-file=path/to/foo.env --from-env-file=path/to/bar.env
```
Create a secret based on a file, directory, or specified literal value.
A single secret may package one or more key/value pairs.
When creating a secret based on a file, the key will default to the basename of the file, and the value will default to the file content. If the basename is an invalid key or you wish to chose your own, you may specify an alternate key.
When creating a secret based on a directory, each file whose basename is a valid key in the directory will be packaged into the secret. Any directory entries except regular files are ignored (e.g. subdirectories, symlinks, devices, pipes, etc).
### Usage
`$ kubectl create generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| append-hash | | false | Append a hash of the secret to its name. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| from-env-file | | [] | Specify the path to a file to read lines of key=val pairs to create a secret. |
| from-file | | [] | Key files can be specified using their file path, in which case a default name will be given to them, or optionally with a name and file path, in which case the given name will be used. Specifying a directory will iterate each named file in the directory that is a valid secret key. |
| from-literal | | [] | Specify a key and literal value to insert in secret (i.e. mykey=somevalue) |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| type | | | The type of secret to create |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*secret tls*
------------
> Create a new TLS secret named tls-secret with the given key pair
>
>
```
kubectl create secret tls tls-secret --cert=path/to/tls.cert --key=path/to/tls.key
```
Create a TLS secret from the given public/private key pair.
The public/private key pair must exist beforehand. The public key certificate must be .PEM encoded and match the given private key.
### Usage
`$ kubectl create tls NAME --cert=path/to/cert/file --key=path/to/key/file [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| append-hash | | false | Append a hash of the secret to its name. |
| cert | | | Path to PEM encoded public key certificate. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| key | | | Path to private key associated with given certificate. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*service*
---------
Create a service using a specified subcommand.
### Usage
`$ kubectl create service`
---
*service clusterip*
-------------------
> Create a new ClusterIP service named my-cs
>
>
```
kubectl create service clusterip my-cs --tcp=5678:8080
```
> Create a new ClusterIP service named my-cs (in headless mode)
>
>
```
kubectl create service clusterip my-cs --clusterip="None"
```
Create a ClusterIP service with the specified name.
### Usage
`$ kubectl create clusterip NAME [--tcp=<port>:<targetPort>] [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| clusterip | | | Assign your own ClusterIP or set to 'None' for a 'headless' service (no loadbalancing). |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| tcp | | [] | Port pairs can be specified as '<port>:<targetPort>'. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*service externalname*
----------------------
> Create a new ExternalName service named my-ns
>
>
```
kubectl create service externalname my-ns --external-name bar.com
```
Create an ExternalName service with the specified name.
ExternalName service references to an external DNS address instead of only pods, which will allow application authors to reference services that exist off platform, on other clusters, or locally.
### Usage
`$ kubectl create externalname NAME --external-name external.name [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| external-name | | | External name of service |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| tcp | | [] | Port pairs can be specified as '<port>:<targetPort>'. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*service loadbalancer*
----------------------
> Create a new LoadBalancer service named my-lbs
>
>
```
kubectl create service loadbalancer my-lbs --tcp=5678:8080
```
Create a LoadBalancer service with the specified name.
### Usage
`$ kubectl create loadbalancer NAME [--tcp=port:targetPort] [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| tcp | | [] | Port pairs can be specified as '<port>:<targetPort>'. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*service nodeport*
------------------
> Create a new NodePort service named my-ns
>
>
```
kubectl create service nodeport my-ns --tcp=5678:8080
```
Create a NodePort service with the specified name.
### Usage
`$ kubectl create nodeport NAME [--tcp=port:targetPort] [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| node-port | | 0 | Port used to expose the service on each node in a cluster. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| tcp | | [] | Port pairs can be specified as '<port>:<targetPort>'. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*serviceaccount*
----------------
> Create a new service account named my-service-account
>
>
```
kubectl create serviceaccount my-service-account
```
Create a service account with the specified name.
### Usage
`$ kubectl create serviceaccount NAME [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-create | Name of the manager used to track field ownership. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
*token*
-------
> Request a token to authenticate to the kube-apiserver as the service account "myapp" in the current namespace
>
>
```
kubectl create token myapp
```
> Request a token for a service account in a custom namespace
>
>
```
kubectl create token myapp --namespace myns
```
> Request a token with a custom expiration
>
>
```
kubectl create token myapp --duration 10m
```
> Request a token with a custom audience
>
>
```
kubectl create token myapp --audience https://example.com
```
> Request a token bound to an instance of a Secret object
>
>
```
kubectl create token myapp --bound-object-kind Secret --bound-object-name mysecret
```
> Request a token bound to an instance of a Secret object with a specific uid
>
>
```
kubectl create token myapp --bound-object-kind Secret --bound-object-name mysecret --bound-object-uid 0d4691ed-659b-4935-a832-355f77ee47cc
```
Request a service account token.
### Usage
`$ kubectl create token SERVICE_ACCOUNT_NAME`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| audience | | [] | Audience of the requested token. If unset, defaults to requesting a token for use with the Kubernetes API server. May be repeated to request a token valid for multiple audiences. |
| bound-object-kind | | | Kind of an object to bind the token to. Supported kinds are Pod, Secret. If set, --bound-object-name must be provided. |
| bound-object-name | | | Name of an object to bind the token to. The token will expire when the object is deleted. Requires --bound-object-kind. |
| bound-object-uid | | | UID of an object to bind the token to. Requires --bound-object-kind and --bound-object-name. If unset, the UID of the existing object is used. |
| duration | | 0s | Requested lifetime of the issued token. The server may return a token with a longer or shorter lifetime. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
get
===
> List all pods in ps output format
>
>
```
kubectl get pods
```
> List all pods in ps output format with more information (such as node name)
>
>
```
kubectl get pods -o wide
```
> List a single replication controller with specified NAME in ps output format
>
>
```
kubectl get replicationcontroller web
```
> List deployments in JSON output format, in the "v1" version of the "apps" API group
>
>
```
kubectl get deployments.v1.apps -o json
```
> List a single pod in JSON output format
>
>
```
kubectl get -o json pod web-pod-13je7
```
> List a pod identified by type and name specified in "pod.yaml" in JSON output format
>
>
```
kubectl get -f pod.yaml -o json
```
> List resources from a directory with kustomization.yaml - e.g. dir/kustomization.yaml
>
>
```
kubectl get -k dir/
```
> Return only the phase value of the specified pod
>
>
```
kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}}
```
> List resource information in custom columns
>
>
```
kubectl get pod test-pod -o custom-columns=CONTAINER:.spec.containers[0].name,IMAGE:.spec.containers[0].image
```
> List all replication controllers and services together in ps output format
>
>
```
kubectl get rc,services
```
> List one or more resources by their type and names
>
>
```
kubectl get rc/web service/frontend pods/web-pod-13je7
```
> List status subresource for a single pod.
>
>
```
kubectl get pod web-pod-13je7 --subresource status
```
Display one or many resources.
Prints a table of the most important information about the specified resources. You can filter the list using a label selector and the --selector flag. If the desired resource type is namespaced you will only see results in your current namespace unless you pass --all-namespaces.
By specifying the output as 'template' and providing a Go template as the value of the --template flag, you can filter the attributes of the fetched resources.
Use "kubectl api-resources" for a complete list of supported resources.
### Usage
`$ kubectl get [(-o|--output=)json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file|custom-columns|custom-columns-file|wide] (TYPE[.VERSION][.GROUP] [NAME | -l label] | TYPE[.VERSION][.GROUP]/NAME ...) [flags]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all-namespaces | A | false | If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| chunk-size | | 500 | Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and may change in the future. |
| field-selector | | | Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to get from a server. |
| ignore-not-found | | false | If the requested object does not exist the command will return exit code 0. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| label-columns | L | [] | Accepts a comma separated list of labels that are going to be presented as columns. Names are case-sensitive. You can also use multiple flag options like -L label1 -L label2... |
| no-headers | | false | When using the default or custom-column output format, don't print headers (default print headers). |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file, custom-columns, custom-columns-file, wide). See custom columns [<https://kubernetes.io/docs/reference/kubectl/#custom-columns>], golang template [<http://golang.org/pkg/text/template/#pkg-overview>] and jsonpath template [<https://kubernetes.io/docs/reference/kubectl/jsonpath/>]. |
| output-watch-events | | false | Output watch event objects when --watch or --watch-only is used. Existing objects are output as initial ADDED events. |
| raw | | | Raw URI to request from the server. Uses the transport specified by the kubeconfig file. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| server-print | | true | If true, have the server return the appropriate table output. Supports extension APIs and CRDs. |
| show-kind | | false | If present, list the resource type for the requested object(s). |
| show-labels | | false | When printing, show all labels as the last column (default hide labels column) |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| sort-by | | | If non-empty, sort list types using this field specification. The field specification is expressed as a JSONPath expression (e.g. '{.metadata.name}'). The field in the API resource specified by this JSONPath expression must be an integer or a string. |
| subresource | | | If specified, gets the subresource of the requested object. Must be one of [status scale]. This flag is alpha and may change in the future. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| use-openapi-print-columns | | false | If true, use x-kubernetes-print-column metadata (if present) from the OpenAPI schema for displaying a resource. |
| watch | w | false | After listing/getting the requested object, watch for changes. |
| watch-only | | false | Watch for changes to the requested object(s), without listing/getting first. |
---
run
===
> Start a nginx pod
>
>
```
kubectl run nginx --image=nginx
```
> Start a hazelcast pod and let the container expose port 5701
>
>
```
kubectl run hazelcast --image=hazelcast/hazelcast --port=5701
```
> Start a hazelcast pod and set environment variables "DNS\_DOMAIN=cluster" and "POD\_NAMESPACE=default" in the container
>
>
```
kubectl run hazelcast --image=hazelcast/hazelcast --env="DNS_DOMAIN=cluster" --env="POD_NAMESPACE=default"
```
> Start a hazelcast pod and set labels "app=hazelcast" and "env=prod" in the container
>
>
```
kubectl run hazelcast --image=hazelcast/hazelcast --labels="app=hazelcast,env=prod"
```
> Dry run; print the corresponding API objects without creating them
>
>
```
kubectl run nginx --image=nginx --dry-run=client
```
> Start a nginx pod, but overload the spec with a partial set of values parsed from JSON
>
>
```
kubectl run nginx --image=nginx --overrides='{ "apiVersion": "v1", "spec": { ... } }'
```
> Start a busybox pod and keep it in the foreground, don't restart it if it exits
>
>
```
kubectl run -i -t busybox --image=busybox --restart=Never
```
> Start the nginx pod using the default command, but use custom arguments (arg1 .. argN) for that command
>
>
```
kubectl run nginx --image=nginx -- <arg1> <arg2> ... <argN>
```
> Start the nginx pod using a different command and custom arguments
>
>
```
kubectl run nginx --image=nginx --command -- <cmd> <arg1> ... <argN>
```
Create and run a particular image in a pod.
### Usage
`$ kubectl run NAME --image=image [--env="key=value"] [--port=port] [--dry-run=server|client] [--overrides=inline-json] [--command] -- [COMMAND] [args...]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| annotations | | [] | Annotations to apply to the pod. |
| attach | | false | If true, wait for the Pod to start running, and then attach to the Pod as if 'kubectl attach ...' were called. Default false, unless '-i/--stdin' is set, in which case the default is true. With '--restart=Never' the exit code of the container process is returned. |
| command | | false | If true and extra arguments are present, use them as the 'command' field in the container, rather than the 'args' field which is the default. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| env | | [] | Environment variables to set in the container. |
| expose | | false | If true, create a ClusterIP service associated with the pod. Requires `--port`. |
| field-manager | | kubectl-run | Name of the manager used to track field ownership. |
| image | | | The image for the container to run. |
| image-pull-policy | | | The image pull policy for the container. If left empty, this value will not be specified by the client and defaulted by the server. |
| labels | l | | Comma separated labels to apply to the pod. Will override previous values. |
| leave-stdin-open | | false | If the pod is started in interactive mode or with stdin, leave stdin open after the first attach completes. By default, stdin will be closed after the first attach completes. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| override-type | | merge | The method used to override the generated object: json, merge, or strategic. |
| overrides | | | An inline JSON override for the generated object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field. |
| pod-running-timeout | | 1m0s | The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running |
| port | | | The port that this container exposes. |
| privileged | | false | If true, run the container in privileged mode. |
| quiet | q | false | If true, suppress prompt messages. |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| restart | | Always | The restart policy for this Pod. Legal values [Always, OnFailure, Never]. |
| rm | | false | If true, delete the pod after it exits. Only valid when attaching to the container, e.g. with '--attach' or with '-i/--stdin'. |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| stdin | i | false | Keep stdin open on the container in the pod, even if nothing is attached. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| tty | t | false | Allocate a TTY for the container in the pod. |
---
expose
======
> Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000
>
>
```
kubectl expose rc nginx --port=80 --target-port=8000
```
> Create a service for a replication controller identified by type and name specified in "nginx-controller.yaml", which serves on port 80 and connects to the containers on port 8000
>
>
```
kubectl expose -f nginx-controller.yaml --port=80 --target-port=8000
```
> Create a service for a pod valid-pod, which serves on port 444 with the name "frontend"
>
>
```
kubectl expose pod valid-pod --port=444 --name=frontend
```
> Create a second service based on the above service, exposing the container port 8443 as port 443 with the name "nginx-https"
>
>
```
kubectl expose service nginx --port=443 --target-port=8443 --name=nginx-https
```
> Create a service for a replicated streaming application on port 4100 balancing UDP traffic and named 'video-stream'.
>
>
```
kubectl expose rc streamer --port=4100 --protocol=UDP --name=video-stream
```
> Create a service for a replicated nginx using replica set, which serves on port 80 and connects to the containers on port 8000
>
>
```
kubectl expose rs nginx --port=80 --target-port=8000
```
> Create a service for an nginx deployment, which serves on port 80 and connects to the containers on port 8000
>
>
```
kubectl expose deployment nginx --port=80 --target-port=8000
```
Expose a resource as a new Kubernetes service.
Looks up a deployment, service, replica set, replication controller or pod by name and uses the selector for that resource as the selector for a new service on the specified port. A deployment or replica set will be exposed as a service only if its selector is convertible to a selector that service supports, i.e. when the selector contains only the matchLabels component. Note that if no port is specified via --port and the exposed resource has multiple ports, all will be re-used by the new service. Also if no labels are specified, the new service will re-use the labels from the resource it exposes.
Possible resources include (case insensitive):
pod (po), service (svc), replicationcontroller (rc), deployment (deploy), replicaset (rs)
### Usage
`$ kubectl expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP|SCTP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| cluster-ip | | | ClusterIP to be assigned to the service. Leave empty to auto-allocate, or set to 'None' to create a headless service. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| external-ip | | | Additional external IP address (not managed by Kubernetes) to accept for the service. If this IP is routed to a node, the service can be accessed by this IP in addition to its generated service IP. |
| field-manager | | kubectl-expose | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to expose a service |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| labels | l | | Labels to apply to the service created by this call. |
| load-balancer-ip | | | IP to assign to the LoadBalancer. If empty, an ephemeral IP will be created and used (cloud-provider specific). |
| name | | | The name for the newly created object. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| override-type | | merge | The method used to override the generated object: json, merge, or strategic. |
| overrides | | | An inline JSON override for the generated object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field. |
| port | | | The port that the service should serve on. Copied from the resource being exposed, if unspecified |
| protocol | | | The network protocol for the service to be created. Default is 'TCP'. |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| selector | | | A label selector to use for this service. Only equality-based selector requirements are supported. If empty (the default) infer the selector from the replication controller or replica set.) |
| session-affinity | | | If non-empty, set the session affinity for the service to this; legal values: 'None', 'ClientIP' |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| target-port | | | Name or number for the port on the container that the service should direct traffic to. Optional. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| type | | | Type for this service: ClusterIP, NodePort, LoadBalancer, or ExternalName. Default is 'ClusterIP'. |
---
delete
======
> Delete a pod using the type and name specified in pod.json
>
>
```
kubectl delete -f ./pod.json
```
> Delete resources from a directory containing kustomization.yaml - e.g. dir/kustomization.yaml
>
>
```
kubectl delete -k dir
```
> Delete resources from all files that end with '.json' - i.e. expand wildcard characters in file names
>
>
```
kubectl delete -f '*.json'
```
> Delete a pod based on the type and name in the JSON passed into stdin
>
>
```
cat pod.json | kubectl delete -f -
```
> Delete pods and services with same names "baz" and "foo"
>
>
```
kubectl delete pod,service baz foo
```
> Delete pods and services with label name=myLabel
>
>
```
kubectl delete pods,services -l name=myLabel
```
> Delete a pod with minimal delay
>
>
```
kubectl delete pod foo --now
```
> Force delete a pod on a dead node
>
>
```
kubectl delete pod foo --force
```
> Delete all pods
>
>
```
kubectl delete pods --all
```
Delete resources by file names, stdin, resources and names, or by resources and label selector.
JSON and YAML formats are accepted. Only one type of argument may be specified: file names, resources and names, or resources and label selector.
Some resources, such as pods, support graceful deletion. These resources define a default period before they are forcibly terminated (the grace period) but you may override that value with the --grace-period flag, or pass --now to set a grace-period of 1. Because these resources often represent entities in the cluster, deletion may not be acknowledged immediately. If the node hosting a pod is down or cannot reach the API server, termination may take significantly longer than the grace period. To force delete a resource, you must specify the --force flag. Note: only a subset of resources support graceful deletion. In absence of the support, the --grace-period flag is ignored.
IMPORTANT: Force deleting pods does not wait for confirmation that the pod's processes have been terminated, which can leave those processes running until the node detects the deletion and completes graceful deletion. If your processes use shared storage or talk to a remote API and depend on the name of the pod to identify themselves, force deleting those pods may result in multiple processes running on different machines using the same identification which may lead to data corruption or inconsistency. Only force delete pods when you are sure the pod is terminated, or if your application can tolerate multiple copies of the same pod running at once. Also, if you force delete pods, the scheduler may place new pods on those nodes before the node has released those resources and causing those pods to be evicted immediately.
Note that the delete command does NOT do resource version checks, so if someone submits an update to a resource right when you submit a delete, their update will be lost along with the rest of the resource.
After a CustomResourceDefinition is deleted, invalidation of discovery cache may take up to 6 hours. If you don't want to wait, you might want to run "kubectl api-resources" to refresh the discovery cache.
### Usage
`$ kubectl delete ([-f FILENAME] | [-k DIRECTORY] | TYPE [(NAME | -l label | --all)])`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | Delete all resources, in the namespace of the specified resource types. |
| all-namespaces | A | false | If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. |
| cascade | | background | Must be "background", "orphan", or "foreground". Selects the deletion cascading strategy for the dependents (e.g. Pods created by a ReplicationController). Defaults to background. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-selector | | | Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type. |
| filename | f | [] | containing the resource to delete. |
| force | | false | If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation. |
| grace-period | | -1 | Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion). |
| ignore-not-found | | false | Treat "resource not found" as a successful delete. Defaults to "true" when --all is specified. |
| kustomize | k | | Process a kustomization directory. This flag can't be used together with -f or -R. |
| now | | false | If true, resources are signaled for immediate shutdown (same as --grace-period=1). |
| output | o | | Output mode. Use "-o name" for shorter output (resource/name). |
| raw | | | Raw URI to DELETE to the server. Uses the transport specified by the kubeconfig file. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| timeout | | 0s | The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object |
| wait | | true | If true, wait for resources to be gone before returning. This waits for finalizers. |
**APP MANAGEMENT**
==================
This section contains commands for creating, updating, deleting, and viewing your workloads in a Kubernetes cluster.
---
apply
=====
> Apply the configuration in pod.json to a pod
>
>
```
kubectl apply -f ./pod.json
```
> Apply resources from a directory containing kustomization.yaml - e.g. dir/kustomization.yaml
>
>
```
kubectl apply -k dir/
```
> Apply the JSON passed into stdin to a pod
>
>
```
cat pod.json | kubectl apply -f -
```
> Apply the configuration from all files that end with '.json' - i.e. expand wildcard characters in file names
>
>
```
kubectl apply -f '*.json'
```
> Note: --prune is still in Alpha # Apply the configuration in manifest.yaml that matches label app=nginx and delete all other resources that are not in the file and match label app=nginx
>
>
```
kubectl apply --prune -f manifest.yaml -l app=nginx
```
> Apply the configuration in manifest.yaml and delete all the other config maps that are not in the file
>
>
```
kubectl apply --prune -f manifest.yaml --all --prune-whitelist=core/v1/ConfigMap
```
Apply a configuration to a resource by file name or stdin. The resource name must be specified. This resource will be created if it doesn't exist yet. To use 'apply', always create the resource initially with either 'apply' or 'create --save-config'.
JSON and YAML formats are accepted.
Alpha Disclaimer: the --prune functionality is not yet complete. Do not use unless you are aware of what the current state is. See <https://issues.k8s.io/34274>.
### Usage
`$ kubectl apply (-f FILENAME | -k DIRECTORY)`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | Select all resources in the namespace of the specified resource types. |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| cascade | | background | Must be "background", "orphan", or "foreground". Selects the deletion cascading strategy for the dependents (e.g. Pods created by a ReplicationController). Defaults to background. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-client-side-apply | Name of the manager used to track field ownership. |
| filename | f | [] | The files that contain the configurations to apply. |
| force | | false | If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation. |
| force-conflicts | | false | If true, server-side apply will force the changes against conflicts. |
| grace-period | | -1 | Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion). |
| kustomize | k | | Process a kustomization directory. This flag can't be used together with -f or -R. |
| openapi-patch | | true | If true, use openapi to calculate diff when the openapi presents and the resource can be found in the openapi spec. Otherwise, fall back to use baked-in types. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| overwrite | | true | Automatically resolve conflicts between the modified and live configuration by using values from the modified configuration |
| prune | | false | Automatically delete resource objects, that do not appear in the configs and are created by either apply or create --save-config. Should be used with either -l or --all. |
| prune-whitelist | | [] | Overwrite the default whitelist with <group/version/kind> for --prune |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| server-side | | false | If true, apply runs in the server instead of the client. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| timeout | | 0s | The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
| wait | | false | If true, wait for resources to be gone before returning. This waits for finalizers. |
---
*edit-last-applied*
-------------------
> Edit the last-applied-configuration annotations by type/name in YAML
>
>
```
kubectl apply edit-last-applied deployment/nginx
```
> Edit the last-applied-configuration annotations by file in JSON
>
>
```
kubectl apply edit-last-applied -f deploy.yaml -o json
```
Edit the latest last-applied-configuration annotations of resources from the default editor.
The edit-last-applied command allows you to directly edit any API resource you can retrieve via the command-line tools. It will open the editor defined by your KUBE\_EDITOR, or EDITOR environment variables, or fall back to 'vi' for Linux or 'notepad' for Windows. You can edit multiple objects, although changes are applied one at a time. The command accepts file names as well as command-line arguments, although the files you point to must be previously saved versions of resources.
The default format is YAML. To edit in JSON, specify "-o json".
The flag --windows-line-endings can be used to force Windows line endings, otherwise the default for your operating system will be used.
In the event an error occurs while updating, a temporary file will be created on disk that contains your unapplied changes. The most common error when updating a resource is another editor changing the resource on the server. When this occurs, you will have to apply your changes to the newer version of the resource, or update your temporary saved copy to include the latest resource version.
### Usage
`$ kubectl apply edit-last-applied (RESOURCE/NAME | -f FILENAME)`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| field-manager | | kubectl-client-side-apply | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files to use to edit the resource |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
| windows-line-endings | | false | Defaults to the line ending native to your platform. |
---
*set-last-applied*
------------------
> Set the last-applied-configuration of a resource to match the contents of a file
>
>
```
kubectl apply set-last-applied -f deploy.yaml
```
> Execute set-last-applied against each configuration file in a directory
>
>
```
kubectl apply set-last-applied -f path/
```
> Set the last-applied-configuration of a resource to match the contents of a file; will create the annotation if it does not already exist
>
>
```
kubectl apply set-last-applied -f deploy.yaml --create-annotation=true
```
Set the latest last-applied-configuration annotations by setting it to match the contents of a file. This results in the last-applied-configuration being updated as though 'kubectl apply -f ' was run, without updating any other parts of the object.
### Usage
`$ kubectl apply set-last-applied -f FILENAME`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| create-annotation | | false | Will create 'last-applied-configuration' annotations if current objects doesn't have one |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| filename | f | [] | Filename, directory, or URL to files that contains the last-applied-configuration annotations |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
*view-last-applied*
-------------------
> View the last-applied-configuration annotations by type/name in YAML
>
>
```
kubectl apply view-last-applied deployment/nginx
```
> View the last-applied-configuration annotations by file in JSON
>
>
```
kubectl apply view-last-applied -f deploy.yaml -o json
```
View the latest last-applied-configuration annotations by type/name or file.
The default output will be printed to stdout in YAML format. You can use the -o option to change the output format.
### Usage
`$ kubectl apply view-last-applied (TYPE [NAME | -l label] | TYPE/NAME | -f FILENAME)`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | Select all resources in the namespace of the specified resource types |
| filename | f | [] | Filename, directory, or URL to files that contains the last-applied-configuration annotations |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| output | o | yaml | Output format. Must be one of (yaml, json) |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
---
annotate
========
> Update pod 'foo' with the annotation 'description' and the value 'my frontend' # If the same annotation is set multiple times, only the last value will be applied
>
>
```
kubectl annotate pods foo description='my frontend'
```
> Update a pod identified by type and name in "pod.json"
>
>
```
kubectl annotate -f pod.json description='my frontend'
```
> Update pod 'foo' with the annotation 'description' and the value 'my frontend running nginx', overwriting any existing value
>
>
```
kubectl annotate --overwrite pods foo description='my frontend running nginx'
```
> Update all pods in the namespace
>
>
```
kubectl annotate pods --all description='my frontend running nginx'
```
> Update pod 'foo' only if the resource is unchanged from version 1
>
>
```
kubectl annotate pods foo description='my frontend running nginx' --resource-version=1
```
> Update pod 'foo' by removing an annotation named 'description' if it exists # Does not require the --overwrite flag
>
>
```
kubectl annotate pods foo description-
```
Update the annotations on one or more resources.
All Kubernetes objects support the ability to store additional data with the object as annotations. Annotations are key/value pairs that can be larger than labels and include arbitrary string values such as structured JSON. Tools and system extensions may use annotations to store their own data.
Attempting to set an annotation that already exists will fail unless --overwrite is set. If --resource-version is specified and does not match the current resource version on the server the command will fail.
Use "kubectl api-resources" for a complete list of supported resources.
### Usage
`$ kubectl annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | Select all resources, in the namespace of the specified resource types. |
| all-namespaces | A | false | If true, check the specified action in all namespaces. |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-annotate | Name of the manager used to track field ownership. |
| field-selector | | | Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to update the annotation |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| list | | false | If true, display the annotations for a given resource. |
| local | | false | If true, annotation will NOT contact api-server but run locally. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| overwrite | | false | If true, allow annotations to be overwritten, otherwise reject annotation updates that overwrite existing annotations. |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| resource-version | | | If non-empty, the annotation update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
autoscale
=========
> Auto scale a deployment "foo", with the number of pods between 2 and 10, no target CPU utilization specified so a default autoscaling policy will be used
>
>
```
kubectl autoscale deployment foo --min=2 --max=10
```
> Auto scale a replication controller "foo", with the number of pods between 1 and 5, target CPU utilization at 80%
>
>
```
kubectl autoscale rc foo --max=5 --cpu-percent=80
```
Creates an autoscaler that automatically chooses and sets the number of pods that run in a Kubernetes cluster.
Looks up a deployment, replica set, stateful set, or replication controller by name and creates an autoscaler that uses the given resource as a reference. An autoscaler can automatically increase or decrease number of pods deployed within the system as needed.
### Usage
`$ kubectl autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| cpu-percent | | -1 | The target average CPU utilization (represented as a percent of requested CPU) over all the pods. If it's not specified or negative, a default autoscaling policy will be used. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-autoscale | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to autoscale. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| max | | -1 | The upper limit for the number of pods that can be set by the autoscaler. Required. |
| min | | -1 | The lower limit for the number of pods that can be set by the autoscaler. If it's not specified or negative, the server will apply a default value. |
| name | | | The name for the newly created object. If not specified, the name of the input resource will be used. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
debug
=====
> Create an interactive debugging session in pod mypod and immediately attach to it. # (requires the EphemeralContainers feature to be enabled in the cluster)
>
>
```
kubectl debug mypod -it --image=busybox
```
> Create a debug container named debugger using a custom automated debugging image. # (requires the EphemeralContainers feature to be enabled in the cluster)
>
>
```
kubectl debug --image=myproj/debug-tools -c debugger mypod
```
> Create a copy of mypod adding a debug container and attach to it
>
>
```
kubectl debug mypod -it --image=busybox --copy-to=my-debugger
```
> Create a copy of mypod changing the command of mycontainer
>
>
```
kubectl debug mypod -it --copy-to=my-debugger --container=mycontainer -- sh
```
> Create a copy of mypod changing all container images to busybox
>
>
```
kubectl debug mypod --copy-to=my-debugger --set-image=*=busybox
```
> Create a copy of mypod adding a debug container and changing container images
>
>
```
kubectl debug mypod -it --copy-to=my-debugger --image=debian --set-image=app=app:debug,sidecar=sidecar:debug
```
> Create an interactive debugging session on a node and immediately attach to it. # The container will run in the host namespaces and the host's filesystem will be mounted at /host
>
>
```
kubectl debug node/mynode -it --image=busybox
```
Debug cluster resources using interactive debugging containers.
'debug' provides automation for common debugging tasks for cluster objects identified by resource and name. Pods will be used by default if no resource is specified.
The action taken by 'debug' varies depending on what resource is specified. Supported actions include:
*Workload: Create a copy of an existing pod with certain attributes changed, for example changing the image tag to a new version.* Workload: Add an ephemeral container to an already running pod, for example to add debugging utilities without restarting the pod.
\* Node: Create a new pod that runs in the node's host namespaces and can access the node's filesystem.
### Usage
`$ kubectl debug (POD | TYPE[[.VERSION].GROUP]/NAME) [ -- COMMAND [args...] ]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| arguments-only | | false | If specified, everything after -- will be passed to the new container as Args instead of Command. |
| attach | | false | If true, wait for the container to start running, and then attach as if 'kubectl attach ...' were called. Default false, unless '-i/--stdin' is set, in which case the default is true. |
| container | c | | Container name to use for debug container. |
| copy-to | | | Create a copy of the target Pod with this name. |
| env | | [] | Environment variables to set in the container. |
| image | | | Container image to use for debug container. |
| image-pull-policy | | | The image pull policy for the container. If left empty, this value will not be specified by the client and defaulted by the server. |
| quiet | q | false | If true, suppress informational messages. |
| replace | | false | When used with '--copy-to', delete the original Pod. |
| same-node | | false | When used with '--copy-to', schedule the copy of target Pod on the same node. |
| set-image | | [] | When used with '--copy-to', a list of name=image pairs for changing container images, similar to how 'kubectl set image' works. |
| share-processes | | true | When used with '--copy-to', enable process namespace sharing in the copy. |
| stdin | i | false | Keep stdin open on the container(s) in the pod, even if nothing is attached. |
| target | | | When using an ephemeral container, target processes in this container name. |
| tty | t | false | Allocate a TTY for the debugging container. |
---
diff
====
> Diff resources included in pod.json
>
>
```
kubectl diff -f pod.json
```
> Diff file read from stdin
>
>
```
cat service.yaml | kubectl diff -f -
```
Diff configurations specified by file name or stdin between the current online configuration, and the configuration as it would be if applied.
The output is always YAML.
KUBECTL\_EXTERNAL\_DIFF environment variable can be used to select your own diff command. Users can use external commands with params too, example: KUBECTL\_EXTERNAL\_DIFF="colordiff -N -u"
By default, the "diff" command available in your path will be run with the "-u" (unified diff) and "-N" (treat absent files as empty) options.
Exit status: 0 No differences were found. 1 Differences were found. >1 Kubectl or diff failed with an error.
Note: KUBECTL\_EXTERNAL\_DIFF, if used, is expected to follow that convention.
### Usage
`$ kubectl diff -f FILENAME`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| field-manager | | kubectl-client-side-apply | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files contains the configuration to diff |
| force-conflicts | | false | If true, server-side apply will force the changes against conflicts. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| prune | | false | Include resources that would be deleted by pruning. Can be used with -l and default shows all resources would be pruned |
| prune-allowlist | | [] | Overwrite the default whitelist with <group/version/kind> for --prune |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| server-side | | false | If true, apply runs in the server instead of the client. |
| show-managed-fields | | false | If true, include managed fields in the diff. |
---
edit
====
> Edit the service named 'registry'
>
>
```
kubectl edit svc/registry
```
> Use an alternative editor
>
>
```
KUBE_EDITOR="nano" kubectl edit svc/registry
```
> Edit the job 'myjob' in JSON using the v1 API format
>
>
```
kubectl edit job.v1.batch/myjob -o json
```
> Edit the deployment 'mydeployment' in YAML and save the modified config in its annotation
>
>
```
kubectl edit deployment/mydeployment -o yaml --save-config
```
> Edit the deployment/mydeployment's status subresource
>
>
```
kubectl edit deployment mydeployment --subresource='status'
```
Edit a resource from the default editor.
The edit command allows you to directly edit any API resource you can retrieve via the command-line tools. It will open the editor defined by your KUBE\_EDITOR, or EDITOR environment variables, or fall back to 'vi' for Linux or 'notepad' for Windows. You can edit multiple objects, although changes are applied one at a time. The command accepts file names as well as command-line arguments, although the files you point to must be previously saved versions of resources.
Editing is done with the API version used to fetch the resource. To edit using a specific API version, fully-qualify the resource, version, and group.
The default format is YAML. To edit in JSON, specify "-o json".
The flag --windows-line-endings can be used to force Windows line endings, otherwise the default for your operating system will be used.
In the event an error occurs while updating, a temporary file will be created on disk that contains your unapplied changes. The most common error when updating a resource is another editor changing the resource on the server. When this occurs, you will have to apply your changes to the newer version of the resource, or update your temporary saved copy to include the latest resource version.
### Usage
`$ kubectl edit (RESOURCE/NAME | -f FILENAME)`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| field-manager | | kubectl-edit | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files to use to edit the resource |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| output-patch | | false | Output the patch if the resource is edited. |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| subresource | | | If specified, edit will operate on the subresource of the requested object. Must be one of [status]. This flag is alpha and may change in the future. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
| windows-line-endings | | false | Defaults to the line ending native to your platform. |
---
kustomize
=========
> Build the current working directory
>
>
```
kubectl kustomize
```
> Build some shared configuration directory
>
>
```
kubectl kustomize /home/config/production
```
> Build from github
>
>
```
kubectl kustomize https://github.com/kubernetes-sigs/kustomize.git/examples/helloWorld?ref=v1.0.6
```
Build a set of KRM resources using a 'kustomization.yaml' file. The DIR argument must be a path to a directory containing 'kustomization.yaml', or a git repository URL with a path suffix specifying same with respect to the repository root. If DIR is omitted, '.' is assumed.
### Usage
`$ kubectl kustomize DIR`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| as-current-user | | false | use the uid and gid of the command executor to run the function in the container |
| enable-alpha-plugins | | false | enable kustomize plugins |
| enable-helm | | false | Enable use of the Helm chart inflator generator. |
| enable-managedby-label | | false | enable adding app.kubernetes.io/managed-by |
| env | e | [] | a list of environment variables to be used by functions |
| helm-command | | helm | helm command (path to executable) |
| load-restrictor | | LoadRestrictionsRootOnly | if set to 'LoadRestrictionsNone', local kustomizations may load files from outside their root. This does, however, break the relocatability of the kustomization. |
| mount | | [] | a list of storage options read from the filesystem |
| network | | false | enable network access for functions that declare it |
| network-name | | bridge | the docker network to run the container in |
| output | o | | If specified, write output to this path. |
| reorder | | legacy | Reorder the resources just before output. Use 'legacy' to apply a legacy reordering (Namespaces first, Webhooks last, etc). Use 'none' to suppress a final reordering. |
---
label
=====
> Update pod 'foo' with the label 'unhealthy' and the value 'true'
>
>
```
kubectl label pods foo unhealthy=true
```
> Update pod 'foo' with the label 'status' and the value 'unhealthy', overwriting any existing value
>
>
```
kubectl label --overwrite pods foo status=unhealthy
```
> Update all pods in the namespace
>
>
```
kubectl label pods --all status=unhealthy
```
> Update a pod identified by the type and name in "pod.json"
>
>
```
kubectl label -f pod.json status=unhealthy
```
> Update pod 'foo' only if the resource is unchanged from version 1
>
>
```
kubectl label pods foo status=unhealthy --resource-version=1
```
> Update pod 'foo' by removing a label named 'bar' if it exists # Does not require the --overwrite flag
>
>
```
kubectl label pods foo bar-
```
Update the labels on a resource.
*A label key and value must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to 63 characters each.* Optionally, the key can begin with a DNS subdomain prefix and a single '/', like example.com/my-app.
*If --overwrite is true, then existing labels can be overwritten, otherwise attempting to overwrite a label will result in an error.* If --resource-version is specified, then updates will use this resource version, otherwise the existing resource-version will be used.
### Usage
`$ kubectl label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | Select all resources, in the namespace of the specified resource types |
| all-namespaces | A | false | If true, check the specified action in all namespaces. |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-label | Name of the manager used to track field ownership. |
| field-selector | | | Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to update the labels |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| list | | false | If true, display the labels for a given resource. |
| local | | false | If true, label will NOT contact api-server but run locally. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| overwrite | | false | If true, allow labels to be overwritten, otherwise reject label updates that overwrite existing labels. |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| resource-version | | | If non-empty, the labels update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
patch
=====
> Partially update a node using a strategic merge patch, specifying the patch as JSON
>
>
```
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
```
> Partially update a node using a strategic merge patch, specifying the patch as YAML
>
>
```
kubectl patch node k8s-node-1 -p $'spec:\n unschedulable: true'
```
> Partially update a node identified by the type and name specified in "node.json" using strategic merge patch
>
>
```
kubectl patch -f node.json -p '{"spec":{"unschedulable":true}}'
```
> Update a container's image; spec.containers[\*].name is required because it's a merge key
>
>
```
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'
```
> Update a container's image using a JSON patch with positional arrays
>
>
```
kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'
```
> Update a deployment's replicas through the scale subresource using a merge patch.
>
>
```
kubectl patch deployment nginx-deployment --subresource='scale' --type='merge' -p '{"spec":{"replicas":2}}'
```
Update fields of a resource using strategic merge patch, a JSON merge patch, or a JSON patch.
JSON and YAML formats are accepted.
### Usage
`$ kubectl patch (-f FILENAME | TYPE NAME) [-p PATCH|--patch-file FILE]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-patch | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to update |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| local | | false | If true, patch will operate on the content of the file, not the server-side resource. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| patch | p | | The patch to be applied to the resource JSON file. |
| patch-file | | | A file containing a patch to be applied to the resource. |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| subresource | | | If specified, patch will operate on the subresource of the requested object. Must be one of [status scale]. This flag is alpha and may change in the future. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| type | | strategic | The type of patch being provided; one of [json merge strategic] |
---
replace
=======
> Replace a pod using the data in pod.json
>
>
```
kubectl replace -f ./pod.json
```
> Replace a pod based on the JSON passed into stdin
>
>
```
cat pod.json | kubectl replace -f -
```
> Update a single-container pod's image version (tag) to v4
>
>
```
kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -
```
> Force replace, delete and then re-create the resource
>
>
```
kubectl replace --force -f ./pod.json
```
Replace a resource by file name or stdin.
JSON and YAML formats are accepted. If replacing an existing resource, the complete resource spec must be provided. This can be obtained by
$ kubectl get TYPE NAME -o yaml
### Usage
`$ kubectl replace -f FILENAME`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| cascade | | background | Must be "background", "orphan", or "foreground". Selects the deletion cascading strategy for the dependents (e.g. Pods created by a ReplicationController). Defaults to background. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-replace | Name of the manager used to track field ownership. |
| filename | f | [] | The files that contain the configurations to replace. |
| force | | false | If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation. |
| grace-period | | -1 | Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion). |
| kustomize | k | | Process a kustomization directory. This flag can't be used together with -f or -R. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| raw | | | Raw URI to PUT to the server. Uses the transport specified by the kubeconfig file. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| save-config | | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| subresource | | | If specified, replace will operate on the subresource of the requested object. Must be one of [status scale]. This flag is alpha and may change in the future. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| timeout | | 0s | The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
| wait | | false | If true, wait for resources to be gone before returning. This waits for finalizers. |
---
rollout
=======
> Rollback to the previous deployment
>
>
```
kubectl rollout undo deployment/abc
```
> Check the rollout status of a daemonset
>
>
```
kubectl rollout status daemonset/foo
```
> Restart a deployment
>
>
```
kubectl rollout restart deployment/abc
```
> Restart deployments with the app=nginx label
>
>
```
kubectl rollout restart deployment --selector=app=nginx
```
Manage the rollout of one or many resources.
Valid resource types include:
*deployments* daemonsets
\* statefulsets
### Usage
`$ kubectl rollout SUBCOMMAND`
---
*history*
---------
> View the rollout history of a deployment
>
>
```
kubectl rollout history deployment/abc
```
> View the details of daemonset revision 3
>
>
```
kubectl rollout history daemonset/abc --revision=3
```
View previous rollout revisions and configurations.
### Usage
`$ kubectl rollout history (TYPE NAME | TYPE/NAME) [flags]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to get from a server. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| revision | | 0 | See the details, including podTemplate of the revision specified |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
*pause*
-------
> Mark the nginx deployment as paused # Any current state of the deployment will continue its function; new updates # to the deployment will not have an effect as long as the deployment is paused
>
>
```
kubectl rollout pause deployment/nginx
```
Mark the provided resource as paused.
Paused resources will not be reconciled by a controller. Use "kubectl rollout resume" to resume a paused resource. Currently only deployments support being paused.
### Usage
`$ kubectl rollout pause RESOURCE`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| field-manager | | kubectl-rollout | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to get from a server. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
*restart*
---------
> Restart a deployment
>
>
```
kubectl rollout restart deployment/nginx
```
> Restart a daemon set
>
>
```
kubectl rollout restart daemonset/abc
```
> Restart deployments with the app=nginx label
>
>
```
kubectl rollout restart deployment --selector=app=nginx
```
Restart a resource.
Resource rollout will be restarted.
### Usage
`$ kubectl rollout restart RESOURCE`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| field-manager | | kubectl-rollout | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to get from a server. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
*resume*
--------
> Resume an already paused deployment
>
>
```
kubectl rollout resume deployment/nginx
```
Resume a paused resource.
Paused resources will not be reconciled by a controller. By resuming a resource, we allow it to be reconciled again. Currently only deployments support being resumed.
### Usage
`$ kubectl rollout resume RESOURCE`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| field-manager | | kubectl-rollout | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to get from a server. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
*status*
--------
> Watch the rollout status of a deployment
>
>
```
kubectl rollout status deployment/nginx
```
Show the status of the rollout.
By default 'rollout status' will watch the status of the latest rollout until it's done. If you don't want to wait for the rollout to finish then you can use --watch=false. Note that if a new rollout starts in-between, then 'rollout status' will continue watching the latest revision. If you want to pin to a specific revision and abort if it is rolled over by another revision, use --revision=N where N is the revision you need to watch for.
### Usage
`$ kubectl rollout status (TYPE NAME | TYPE/NAME) [flags]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to get from a server. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| revision | | 0 | Pin to a specific revision for showing its status. Defaults to 0 (last revision). |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| timeout | | 0s | The length of time to wait before ending watch, zero means never. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h). |
| watch | w | true | Watch the status of the rollout until it's done. |
---
*undo*
------
> Roll back to the previous deployment
>
>
```
kubectl rollout undo deployment/abc
```
> Roll back to daemonset revision 3
>
>
```
kubectl rollout undo daemonset/abc --to-revision=3
```
> Roll back to the previous deployment with dry-run
>
>
```
kubectl rollout undo --dry-run=server deployment/abc
```
Roll back to a previous rollout.
### Usage
`$ kubectl rollout undo (TYPE NAME | TYPE/NAME) [flags]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to get from a server. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| to-revision | | 0 | The revision to rollback to. Default to 0 (last revision). |
---
scale
=====
> Scale a replica set named 'foo' to 3
>
>
```
kubectl scale --replicas=3 rs/foo
```
> Scale a resource identified by type and name specified in "foo.yaml" to 3
>
>
```
kubectl scale --replicas=3 -f foo.yaml
```
> If the deployment named mysql's current size is 2, scale mysql to 3
>
>
```
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
```
> Scale multiple replication controllers
>
>
```
kubectl scale --replicas=5 rc/foo rc/bar rc/baz
```
> Scale stateful set named 'web' to 3
>
>
```
kubectl scale --replicas=3 statefulset/web
```
Set a new size for a deployment, replica set, replication controller, or stateful set.
Scale also allows users to specify one or more preconditions for the scale action.
If --current-replicas or --resource-version is specified, it is validated before the scale is attempted, and it is guaranteed that the precondition holds true when the scale is sent to the server.
### Usage
`$ kubectl scale [--resource-version=version] [--current-replicas=count] --replicas=COUNT (-f FILENAME | TYPE NAME)`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | Select all resources in the namespace of the specified resource types |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| current-replicas | | -1 | Precondition for current size. Requires that the current size of the resource match this value in order to scale. -1 (default) for no condition. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to set a new size |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| replicas | | 0 | The new desired number of replicas. Required. |
| resource-version | | | Precondition for resource version. Requires that the current resource version match this value in order to scale. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| timeout | | 0s | The length of time to wait before giving up on a scale operation, zero means don't wait. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h). |
---
set
===
Configure application resources.
These commands help you make changes to existing application resources.
### Usage
`$ kubectl set SUBCOMMAND`
---
*env*
-----
> Update deployment 'registry' with a new environment variable
>
>
```
kubectl set env deployment/registry STORAGE_DIR=/local
```
> List the environment variables defined on a deployments 'sample-build'
>
>
```
kubectl set env deployment/sample-build --list
```
> List the environment variables defined on all pods
>
>
```
kubectl set env pods --all --list
```
> Output modified deployment in YAML, and does not alter the object on the server
>
>
```
kubectl set env deployment/sample-build STORAGE_DIR=/data -o yaml
```
> Update all containers in all replication controllers in the project to have ENV=prod
>
>
```
kubectl set env rc --all ENV=prod
```
> Import environment from a secret
>
>
```
kubectl set env --from=secret/mysecret deployment/myapp
```
> Import environment from a config map with a prefix
>
>
```
kubectl set env --from=configmap/myconfigmap --prefix=MYSQL_ deployment/myapp
```
> Import specific keys from a config map
>
>
```
kubectl set env --keys=my-example-key --from=configmap/myconfigmap deployment/myapp
```
> Remove the environment variable ENV from container 'c1' in all deployment configs
>
>
```
kubectl set env deployments --all --containers="c1" ENV-
```
> Remove the environment variable ENV from a deployment definition on disk and # update the deployment config on the server
>
>
```
kubectl set env -f deploy.json ENV-
```
> Set some of the local shell environment into a deployment config on the server
>
>
```
env | grep RAILS_ | kubectl set env -e - deployment/registry
```
Update environment variables on a pod template.
List environment variable definitions in one or more pods, pod templates. Add, update, or remove container environment variable definitions in one or more pod templates (within replication controllers or deployment configurations). View or modify the environment variable definitions on all containers in the specified pods or pod templates, or just those that match a wildcard.
If "--env -" is passed, environment variables can be read from STDIN using the standard env syntax.
Possible resources include (case insensitive):
pod (po), replicationcontroller (rc), deployment (deploy), daemonset (ds), statefulset (sts), cronjob (cj), replicaset (rs)
### Usage
`$ kubectl set env RESOURCE/NAME KEY_1=VAL_1 ... KEY_N=VAL_N`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | If true, select all resources in the namespace of the specified resource types |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| containers | c | \* | The names of containers in the selected pod templates to change - may use wildcards |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| env | e | [] | Specify a key-value pair for an environment variable to set into each container. |
| field-manager | | kubectl-set | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files the resource to update the env |
| from | | | The name of a resource from which to inject environment variables |
| keys | | [] | Comma-separated list of keys to import from specified resource |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| list | | false | If true, display the environment and any changes in the standard format. this flag will removed when we have kubectl view env. |
| local | | false | If true, set env will NOT contact api-server but run locally. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| overwrite | | true | If true, allow environment to be overwritten, otherwise reject updates that overwrite existing environment. |
| prefix | | | Prefix to append to variable names |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| resolve | | false | If true, show secret or configmap references when listing variables |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
*image*
-------
> Set a deployment's nginx container image to 'nginx:1.9.1', and its busybox container image to 'busybox'
>
>
```
kubectl set image deployment/nginx busybox=busybox nginx=nginx:1.9.1
```
> Update all deployments' and rc's nginx container's image to 'nginx:1.9.1'
>
>
```
kubectl set image deployments,rc nginx=nginx:1.9.1 --all
```
> Update image of all containers of daemonset abc to 'nginx:1.9.1'
>
>
```
kubectl set image daemonset abc *=nginx:1.9.1
```
> Print result (in yaml format) of updating nginx container image from local file, without hitting the server
>
>
```
kubectl set image -f path/to/file.yaml nginx=nginx:1.9.1 --local -o yaml
```
Update existing container image(s) of resources.
Possible resources include (case insensitive):
pod (po), replicationcontroller (rc), deployment (deploy), daemonset (ds), statefulset (sts), cronjob (cj), replicaset (rs)
### Usage
`$ kubectl set image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | Select all resources, in the namespace of the specified resource types |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-set | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to get from a server. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| local | | false | If true, set image will NOT contact api-server but run locally. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
*resources*
-----------
> Set a deployments nginx container cpu limits to "200m" and memory to "512Mi"
>
>
```
kubectl set resources deployment nginx -c=nginx --limits=cpu=200m,memory=512Mi
```
> Set the resource request and limits for all containers in nginx
>
>
```
kubectl set resources deployment nginx --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256Mi
```
> Remove the resource requests for resources on containers in nginx
>
>
```
kubectl set resources deployment nginx --limits=cpu=0,memory=0 --requests=cpu=0,memory=0
```
> Print the result (in yaml format) of updating nginx container limits from a local, without hitting the server
>
>
```
kubectl set resources -f path/to/file.yaml --limits=cpu=200m,memory=512Mi --local -o yaml
```
Specify compute resource requirements (CPU, memory) for any resource that defines a pod template. If a pod is successfully scheduled, it is guaranteed the amount of resource requested, but may burst up to its specified limits.
For each compute resource, if a limit is specified and a request is omitted, the request will default to the limit.
Possible resources include (case insensitive): Use "kubectl api-resources" for a complete list of supported resources..
### Usage
`$ kubectl set resources (-f FILENAME | TYPE NAME) ([--limits=LIMITS & --requests=REQUESTS]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | Select all resources, in the namespace of the specified resource types |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| containers | c | \* | The names of containers in the selected pod templates to change, all containers are selected by default - may use wildcards |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-set | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to get from a server. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| limits | | | The resource requirement requests for this container. For example, 'cpu=100m,memory=256Mi'. Note that server side components may assign requests depending on the server configuration, such as limit ranges. |
| local | | false | If true, set resources will NOT contact api-server but run locally. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| requests | | | The resource requirement requests for this container. For example, 'cpu=100m,memory=256Mi'. Note that server side components may assign requests depending on the server configuration, such as limit ranges. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
*selector*
----------
> Set the labels and selector before creating a deployment/service pair
>
>
```
kubectl create service clusterip my-svc --clusterip="None" -o yaml --dry-run=client | kubectl set selector --local -f - 'environment=qa' -o yaml | kubectl create -f - kubectl create deployment my-dep -o yaml --dry-run=client | kubectl label --local -f - environment=qa -o yaml | kubectl create -f -
```
Set the selector on a resource. Note that the new selector will overwrite the old selector if the resource had one prior to the invocation of 'set selector'.
A selector must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to 63 characters. If --resource-version is specified, then updates will use this resource version, otherwise the existing resource-version will be used. Note: currently selectors can only be set on Service objects.
### Usage
`$ kubectl set selector (-f FILENAME | TYPE NAME) EXPRESSIONS [--resource-version=version]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | Select all resources in the namespace of the specified resource types |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-set | Name of the manager used to track field ownership. |
| filename | f | [] | identifying the resource. |
| local | | false | If true, annotation will NOT contact api-server but run locally. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | true | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| resource-version | | | If non-empty, the selectors update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
*serviceaccount*
----------------
> Set deployment nginx-deployment's service account to serviceaccount1
>
>
```
kubectl set serviceaccount deployment nginx-deployment serviceaccount1
```
> Print the result (in YAML format) of updated nginx deployment with the service account from local file, without hitting the API server
>
>
```
kubectl set sa -f nginx-deployment.yaml serviceaccount1 --local --dry-run=client -o yaml
```
Update the service account of pod template resources.
Possible resources (case insensitive) can be:
replicationcontroller (rc), deployment (deploy), daemonset (ds), job, replicaset (rs), statefulset
### Usage
`$ kubectl set serviceaccount (-f FILENAME | TYPE NAME) SERVICE_ACCOUNT`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | Select all resources, in the namespace of the specified resource types |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-set | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to get from a server. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| local | | false | If true, set serviceaccount will NOT contact api-server but run locally. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| record | | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
*subject*
---------
> Update a cluster role binding for serviceaccount1
>
>
```
kubectl set subject clusterrolebinding admin --serviceaccount=namespace:serviceaccount1
```
> Update a role binding for user1, user2, and group1
>
>
```
kubectl set subject rolebinding admin --user=user1 --user=user2 --group=group1
```
> Print the result (in YAML format) of updating rolebinding subjects from a local, without hitting the server
>
>
```
kubectl create rolebinding admin --role=admin --user=admin -o yaml --dry-run=client | kubectl set subject --local -f - --user=foo -o yaml
```
Update the user, group, or service account in a role binding or cluster role binding.
### Usage
`$ kubectl set subject (-f FILENAME | TYPE NAME) [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run=server|client|none]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | Select all resources, in the namespace of the specified resource types |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-set | Name of the manager used to track field ownership. |
| filename | f | [] | Filename, directory, or URL to files the resource to update the subjects |
| group | | [] | Groups to bind to the role |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| local | | false | If true, set subject will NOT contact api-server but run locally. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| serviceaccount | | [] | Service accounts to bind to the role |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
wait
====
> Wait for the pod "busybox1" to contain the status condition of type "Ready"
>
>
```
kubectl wait --for=condition=Ready pod/busybox1
```
> The default value of status condition is true; you can wait for other targets after an equal delimiter (compared after Unicode simple case folding, which is a more general form of case-insensitivity):
>
>
```
kubectl wait --for=condition=Ready=false pod/busybox1
```
> Wait for the pod "busybox1" to contain the status phase to be "Running".
>
>
```
kubectl wait --for=jsonpath='{.status.phase}'=Running pod/busybox1
```
> Wait for the pod "busybox1" to be deleted, with a timeout of 60s, after having issued the "delete" command
>
>
```
kubectl delete pod/busybox1 kubectl wait --for=delete pod/busybox1 --timeout=60s
```
Experimental: Wait for a specific condition on one or many resources.
The command takes multiple resources and waits until the specified condition is seen in the Status field of every given resource.
Alternatively, the command can wait for the given set of resources to be deleted by providing the "delete" keyword as the value to the --for flag.
A successful message will be printed to stdout indicating when the specified condition has been met. You can use -o option to change to output destination.
### Usage
`$ kubectl wait ([-f FILENAME] | resource.group/resource.name | resource.group [(-l label | --all)]) [--for=delete|--for condition=available|--for=jsonpath='{}'=value]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | Select all resources in the namespace of the specified resource types |
| all-namespaces | A | false | If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| field-selector | | | Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type. |
| filename | f | [] | identifying the resource. |
| for | | | The condition to wait on: [delete|condition=condition-name[=condition-value]|jsonpath='{JSONPath expression}'=JSONPath Condition]. The default condition-value is true. Condition values are compared after Unicode simple case folding, which is a more general form of case-insensitivity. |
| local | | false | If true, annotation will NOT contact api-server but run locally. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| recursive | R | true | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2) |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| timeout | | 30s | The length of time to wait before giving up. Zero means check once and don't wait, negative means wait for a week. |
**WORKING WITH APPS**
=====================
This section contains commands for inspecting and debugging your applications.
* `logs` will print the logs from the specified pod + container.
* `exec` can be used to get an interactive shell on a pod + container.
* `describe` will print debug information about the given resource.
---
attach
======
> Get output from running pod mypod; use the 'kubectl.kubernetes.io/default-container' annotation # for selecting the container to be attached or the first container in the pod will be chosen
>
>
```
kubectl attach mypod
```
> Get output from ruby-container from pod mypod
>
>
```
kubectl attach mypod -c ruby-container
```
> Switch to raw terminal mode; sends stdin to 'bash' in ruby-container from pod mypod # and sends stdout/stderr from 'bash' back to the client
>
>
```
kubectl attach mypod -c ruby-container -i -t
```
> Get output from the first pod of a replica set named nginx
>
>
```
kubectl attach rs/nginx
```
Attach to a process that is already running inside an existing container.
### Usage
`$ kubectl attach (POD | TYPE/NAME) -c CONTAINER`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| container | c | | Container name. If omitted, use the kubectl.kubernetes.io/default-container annotation for selecting the container to be attached or the first container in the pod will be chosen |
| pod-running-timeout | | 1m0s | The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running |
| quiet | q | false | Only print output from the remote session |
| stdin | i | false | Pass stdin to the container |
| tty | t | false | Stdin is a TTY |
---
auth
====
Inspect authorization
### Usage
`$ kubectl auth`
---
*can-i*
-------
> Check to see if I can create pods in any namespace
>
>
```
kubectl auth can-i create pods --all-namespaces
```
> Check to see if I can list deployments in my current namespace
>
>
```
kubectl auth can-i list deployments.apps
```
> Check to see if I can do everything in my current namespace ("\*" means all)
>
>
```
kubectl auth can-i '*' '*'
```
> Check to see if I can get the job named "bar" in namespace "foo"
>
>
```
kubectl auth can-i list jobs.batch/bar -n foo
```
> Check to see if I can read pod logs
>
>
```
kubectl auth can-i get pods --subresource=log
```
> Check to see if I can access the URL /logs/
>
>
```
kubectl auth can-i get /logs/
```
> List all allowed actions in namespace "foo"
>
>
```
kubectl auth can-i --list --namespace=foo
```
Check whether an action is allowed.
VERB is a logical Kubernetes API verb like 'get', 'list', 'watch', 'delete', etc. TYPE is a Kubernetes resource. Shortcuts and groups will be resolved. NONRESOURCEURL is a partial URL that starts with "/". NAME is the name of a particular Kubernetes resource. This command pairs nicely with impersonation. See --as global flag.
### Usage
`$ kubectl auth can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all-namespaces | A | false | If true, check the specified action in all namespaces. |
| list | | false | If true, prints all allowed actions. |
| no-headers | | false | If true, prints allowed actions without headers |
| quiet | q | false | If true, suppress output and just return the exit code. |
| subresource | | | SubResource such as pod/log or deployment/scale |
---
*reconcile*
-----------
> Reconcile RBAC resources from a file
>
>
```
kubectl auth reconcile -f my-rbac-rules.yaml
```
Reconciles rules for RBAC role, role binding, cluster role, and cluster role binding objects.
Missing objects are created, and the containing namespace is created for namespaced objects, if required.
Existing roles are updated to include the permissions in the input objects, and remove extra permissions if --remove-extra-permissions is specified.
Existing bindings are updated to include the subjects in the input objects, and remove extra subjects if --remove-extra-subjects is specified.
This is preferred to 'apply' for RBAC resources so that semantically-aware merging of rules and subjects is done.
### Usage
`$ kubectl auth reconcile -f FILENAME`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to reconcile. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| remove-extra-permissions | | false | If true, removes extra permissions added to roles |
| remove-extra-subjects | | false | If true, removes extra subjects added to rolebindings |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
cp
==
> !!!Important Note!!! # Requires that the 'tar' binary is present in your container # image. If 'tar' is not present, 'kubectl cp' will fail. # # For advanced use cases, such as symlinks, wildcard expansion or # file mode preservation, consider using 'kubectl exec'. # Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace
>
>
```
tar cf - /tmp/foo | kubectl exec -i -n <some-namespace> <some-pod> -- tar xf - -C /tmp/bar
```
> Copy /tmp/foo from a remote pod to /tmp/bar locally
>
>
```
kubectl exec -n <some-namespace> <some-pod> -- tar cf - /tmp/foo | tar xf - -C /tmp/bar
```
> Copy /tmp/foo\_dir local directory to /tmp/bar\_dir in a remote pod in the default namespace
>
>
```
kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir
```
> Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container
>
>
```
kubectl cp /tmp/foo <some-pod>:/tmp/bar -c <specific-container>
```
> Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace
>
>
```
kubectl cp /tmp/foo <some-namespace>/<some-pod>:/tmp/bar
```
> Copy /tmp/foo from a remote pod to /tmp/bar locally
>
>
```
kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar
```
Copy files and directories to and from containers.
### Usage
`$ kubectl cp <file-spec-src> <file-spec-dest>`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| container | c | | Container name. If omitted, use the kubectl.kubernetes.io/default-container annotation for selecting the container to be attached or the first container in the pod will be chosen |
| no-preserve | | false | The copied file/directory's ownership and permissions will not be preserved in the container |
| retries | | 0 | Set number of retries to complete a copy operation from a container. Specify 0 to disable or any negative value for infinite retrying. The default is 0 (no retry). |
---
describe
========
> Describe a node
>
>
```
kubectl describe nodes kubernetes-node-emt8.c.myproject.internal
```
> Describe a pod
>
>
```
kubectl describe pods/nginx
```
> Describe a pod identified by type and name in "pod.json"
>
>
```
kubectl describe -f pod.json
```
> Describe all pods
>
>
```
kubectl describe pods
```
> Describe pods by label name=myLabel
>
>
```
kubectl describe po -l name=myLabel
```
> Describe all pods managed by the 'frontend' replication controller # (rc-created pods get the name of the rc as a prefix in the pod name)
>
>
```
kubectl describe pods frontend
```
Show details of a specific resource or group of resources.
Print a detailed description of the selected resources, including related resources such as events or controllers. You may select a single object by name, all objects of that type, provide a name prefix, or label selector. For example:
$ kubectl describe TYPE NAME\_PREFIX
will first check for an exact match on TYPE and NAME\_PREFIX. If no such resource exists, it will output details for every resource that has a name prefixed with NAME\_PREFIX.
Use "kubectl api-resources" for a complete list of supported resources.
### Usage
`$ kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME)`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all-namespaces | A | false | If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. |
| chunk-size | | 500 | Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and may change in the future. |
| filename | f | [] | Filename, directory, or URL to files containing the resource to describe |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-events | | true | If true, display events related to the described object. |
---
exec
====
> Get output from running the 'date' command from pod mypod, using the first container by default
>
>
```
kubectl exec mypod -- date
```
> Get output from running the 'date' command in ruby-container from pod mypod
>
>
```
kubectl exec mypod -c ruby-container -- date
```
> Switch to raw terminal mode; sends stdin to 'bash' in ruby-container from pod mypod # and sends stdout/stderr from 'bash' back to the client
>
>
```
kubectl exec mypod -c ruby-container -i -t -- bash -il
```
> List contents of /usr from the first container of pod mypod and sort by modification time # If the command you want to execute in the pod has any flags in common (e.g. -i), # you must use two dashes (--) to separate your command's flags/arguments # Also note, do not surround your command and its flags/arguments with quotes # unless that is how you would execute it normally (i.e., do ls -t /usr, not "ls -t /usr")
>
>
```
kubectl exec mypod -i -t -- ls -t /usr
```
> Get output from running 'date' command from the first pod of the deployment mydeployment, using the first container by default
>
>
```
kubectl exec deploy/mydeployment -- date
```
> Get output from running 'date' command from the first pod of the service myservice, using the first container by default
>
>
```
kubectl exec svc/myservice -- date
```
Execute a command in a container.
### Usage
`$ kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| container | c | | Container name. If omitted, use the kubectl.kubernetes.io/default-container annotation for selecting the container to be attached or the first container in the pod will be chosen |
| filename | f | [] | to use to exec into the resource |
| pod-running-timeout | | 1m0s | The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running |
| quiet | q | false | Only print output from the remote session |
| stdin | i | false | Pass stdin to the container |
| tty | t | false | Stdin is a TTY |
---
logs
====
> Return snapshot logs from pod nginx with only one container
>
>
```
kubectl logs nginx
```
> Return snapshot logs from pod nginx with multi containers
>
>
```
kubectl logs nginx --all-containers=true
```
> Return snapshot logs from all containers in pods defined by label app=nginx
>
>
```
kubectl logs -l app=nginx --all-containers=true
```
> Return snapshot of previous terminated ruby container logs from pod web-1
>
>
```
kubectl logs -p -c ruby web-1
```
> Begin streaming the logs of the ruby container in pod web-1
>
>
```
kubectl logs -f -c ruby web-1
```
> Begin streaming the logs from all containers in pods defined by label app=nginx
>
>
```
kubectl logs -f -l app=nginx --all-containers=true
```
> Display only the most recent 20 lines of output in pod nginx
>
>
```
kubectl logs --tail=20 nginx
```
> Show all logs from pod nginx written in the last hour
>
>
```
kubectl logs --since=1h nginx
```
> Show logs from a kubelet with an expired serving certificate
>
>
```
kubectl logs --insecure-skip-tls-verify-backend nginx
```
> Return snapshot logs from first container of a job named hello
>
>
```
kubectl logs job/hello
```
> Return snapshot logs from container nginx-1 of a deployment named nginx
>
>
```
kubectl logs deployment/nginx -c nginx-1
```
Print the logs for a container in a pod or specified resource. If the pod has only one container, the container name is optional.
### Usage
`$ kubectl logs [-f] [-p] (POD | TYPE/NAME) [-c CONTAINER]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all-containers | | false | Get all containers' logs in the pod(s). |
| container | c | | Print the logs of this container |
| follow | f | false | Specify if the logs should be streamed. |
| ignore-errors | | false | If watching / following pod logs, allow for any errors that occur to be non-fatal |
| insecure-skip-tls-verify-backend | | false | Skip verifying the identity of the kubelet that logs are requested from. In theory, an attacker could provide invalid log content back. You might want to use this if your kubelet serving certificates have expired. |
| limit-bytes | | 0 | Maximum bytes of logs to return. Defaults to no limit. |
| max-log-requests | | 5 | Specify maximum number of concurrent logs to follow when using by a selector. Defaults to 5. |
| pod-running-timeout | | 20s | The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running |
| prefix | | false | Prefix each log line with the log source (pod name and container name) |
| previous | p | false | If true, print the logs for the previous instance of the container in a pod if it exists. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| since | | 0s | Only return logs newer than a relative duration like 5s, 2m, or 3h. Defaults to all logs. Only one of since-time / since may be used. |
| since-time | | | Only return logs after a specific date (RFC3339). Defaults to all logs. Only one of since-time / since may be used. |
| tail | | -1 | Lines of recent log file to display. Defaults to -1 with no selector, showing all log lines otherwise 10, if a selector is provided. |
| timestamps | | false | Include timestamps on each line in the log output |
---
port-forward
============
> Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod
>
>
```
kubectl port-forward pod/mypod 5000 6000
```
> Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod selected by the deployment
>
>
```
kubectl port-forward deployment/mydeployment 5000 6000
```
> Listen on port 8443 locally, forwarding to the targetPort of the service's port named "https" in a pod selected by the service
>
>
```
kubectl port-forward service/myservice 8443:https
```
> Listen on port 8888 locally, forwarding to 5000 in the pod
>
>
```
kubectl port-forward pod/mypod 8888:5000
```
> Listen on port 8888 on all addresses, forwarding to 5000 in the pod
>
>
```
kubectl port-forward --address 0.0.0.0 pod/mypod 8888:5000
```
> Listen on port 8888 on localhost and selected IP, forwarding to 5000 in the pod
>
>
```
kubectl port-forward --address localhost,10.19.21.23 pod/mypod 8888:5000
```
> Listen on a random port locally, forwarding to 5000 in the pod
>
>
```
kubectl port-forward pod/mypod :5000
```
Forward one or more local ports to a pod.
Use resource type/name such as deployment/mydeployment to select a pod. Resource type defaults to 'pod' if omitted.
If there are multiple pods matching the criteria, a pod will be selected automatically. The forwarding session ends when the selected pod terminates, and a rerun of the command is needed to resume forwarding.
### Usage
`$ kubectl port-forward TYPE/NAME [options] [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| address | | [localhost] | Addresses to listen on (comma separated). Only accepts IP addresses or localhost as a value. When localhost is supplied, kubectl will try to bind on both 127.0.0.1 and ::1 and will fail if neither of these addresses are available to bind. |
| pod-running-timeout | | 1m0s | The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running |
---
proxy
=====
> To proxy all of the Kubernetes API and nothing else
>
>
```
kubectl proxy --api-prefix=/
```
> To proxy only part of the Kubernetes API and also some static files # You can get pods info with 'curl localhost:8001/api/v1/pods'
>
>
```
kubectl proxy --www=/my/files --www-prefix=/static/ --api-prefix=/api/
```
> To proxy the entire Kubernetes API at a different root # You can get pods info with 'curl localhost:8001/custom/api/v1/pods'
>
>
```
kubectl proxy --api-prefix=/custom/
```
> Run a proxy to the Kubernetes API server on port 8011, serving static content from ./local/www/
>
>
```
kubectl proxy --port=8011 --www=./local/www/
```
> Run a proxy to the Kubernetes API server on an arbitrary local port # The chosen port for the server will be output to stdout
>
>
```
kubectl proxy --port=0
```
> Run a proxy to the Kubernetes API server, changing the API prefix to k8s-api # This makes e.g. the pods API available at localhost:8001/k8s-api/v1/pods/
>
>
```
kubectl proxy --api-prefix=/k8s-api
```
Creates a proxy server or application-level gateway between localhost and the Kubernetes API server. It also allows serving static content over specified HTTP path. All incoming data enters through one port and gets forwarded to the remote Kubernetes API server port, except for the path matching the static content path.
### Usage
`$ kubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| accept-hosts | | ^localhost$,^127.0.0.1$,^[::1]$ | Regular expression for hosts that the proxy should accept. |
| accept-paths | | ^.\* | Regular expression for paths that the proxy should accept. |
| address | | 127.0.0.1 | The IP address on which to serve on. |
| api-prefix | | / | Prefix to serve the proxied API under. |
| append-server-path | | false | If true, enables automatic path appending of the kube context server path to each request. |
| disable-filter | | false | If true, disable request filtering in the proxy. This is dangerous, and can leave you vulnerable to XSRF attacks, when used with an accessible port. |
| keepalive | | 0s | keepalive specifies the keep-alive period for an active network connection. Set to 0 to disable keepalive. |
| port | p | 8001 | The port on which to run the proxy. Set to 0 to pick a random port. |
| reject-methods | | ^$ | Regular expression for HTTP methods that the proxy should reject (example --reject-methods='POST,PUT,PATCH'). |
| reject-paths | | ^/api/.*/pods/.*/exec,^/api/.*/pods/.*/attach | Regular expression for paths that the proxy should reject. Paths specified here will be rejected even accepted by --accept-paths. |
| unix-socket | u | | Unix socket on which to run the proxy. |
| www | w | | Also serve static files from the given directory under the specified prefix. |
| www-prefix | P | /static/ | Prefix to serve static files under, if static file directory is specified. |
---
top
===
Display Resource (CPU/Memory) usage.
The top command allows you to see the resource consumption for nodes or pods.
This command requires Metrics Server to be correctly configured and working on the server.
### Usage
`$ kubectl top`
---
*node*
------
> Show metrics for all nodes
>
>
```
kubectl top node
```
> Show metrics for a given node
>
>
```
kubectl top node NODE_NAME
```
Display resource (CPU/memory) usage of nodes.
The top-node command allows you to see the resource consumption of nodes.
### Usage
`$ kubectl top node [NAME | -l label]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| no-headers | | false | If present, print output without headers |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-capacity | | false | Print node resources based on Capacity instead of Allocatable(default) of the nodes. |
| sort-by | | | If non-empty, sort nodes list using specified field. The field can be either 'cpu' or 'memory'. |
| use-protocol-buffers | | true | Enables using protocol-buffers to access Metrics API. |
---
*pod*
-----
> Show metrics for all pods in the default namespace
>
>
```
kubectl top pod
```
> Show metrics for all pods in the given namespace
>
>
```
kubectl top pod --namespace=NAMESPACE
```
> Show metrics for a given pod and its containers
>
>
```
kubectl top pod POD_NAME --containers
```
> Show metrics for the pods defined by label name=myLabel
>
>
```
kubectl top pod -l name=myLabel
```
Display resource (CPU/memory) usage of pods.
The 'top pod' command allows you to see the resource consumption of pods.
Due to the metrics pipeline delay, they may be unavailable for a few minutes since pod creation.
### Usage
`$ kubectl top pod [NAME | -l label]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all-namespaces | A | false | If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. |
| containers | | false | If present, print usage of containers within a pod. |
| field-selector | | | Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type. |
| no-headers | | false | If present, print output without headers. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| sort-by | | | If non-empty, sort pods list using specified field. The field can be either 'cpu' or 'memory'. |
| sum | | false | Print the sum of the resource usage |
| use-protocol-buffers | | true | Enables using protocol-buffers to access Metrics API. |
**CLUSTER MANAGEMENT**
======================
---
api-versions
============
> Print the supported API versions
>
>
```
kubectl api-versions
```
Print the supported API versions on the server, in the form of "group/version".
### Usage
`$ kubectl api-versions`
---
certificate
===========
Modify certificate resources.
### Usage
`$ kubectl certificate SUBCOMMAND`
---
*approve*
---------
> Approve CSR 'csr-sqgzp'
>
>
```
kubectl certificate approve csr-sqgzp
```
Approve a certificate signing request.
kubectl certificate approve allows a cluster admin to approve a certificate signing request (CSR). This action tells a certificate signing controller to issue a certificate to the requestor with the attributes requested in the CSR.
SECURITY NOTICE: Depending on the requested attributes, the issued certificate can potentially grant a requester access to cluster resources or to authenticate as a requested identity. Before approving a CSR, ensure you understand what the signed certificate can do.
### Usage
`$ kubectl certificate approve (-f FILENAME | NAME)`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to update |
| force | | false | Update the CSR even if it is already approved. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
*deny*
------
> Deny CSR 'csr-sqgzp'
>
>
```
kubectl certificate deny csr-sqgzp
```
Deny a certificate signing request.
kubectl certificate deny allows a cluster admin to deny a certificate signing request (CSR). This action tells a certificate signing controller to not to issue a certificate to the requestor.
### Usage
`$ kubectl certificate deny (-f FILENAME | NAME)`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| filename | f | [] | Filename, directory, or URL to files identifying the resource to update |
| force | | false | Update the CSR even if it is already denied. |
| kustomize | k | | Process the kustomization directory. This flag can't be used together with -f or -R. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
cluster-info
============
> Print the address of the control plane and cluster services
>
>
```
kubectl cluster-info
```
Display addresses of the control plane and services with label kubernetes.io/cluster-service=true. To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
### Usage
`$ kubectl cluster-info`
---
*dump*
------
> Dump current cluster state to stdout
>
>
```
kubectl cluster-info dump
```
> Dump current cluster state to /path/to/cluster-state
>
>
```
kubectl cluster-info dump --output-directory=/path/to/cluster-state
```
> Dump all namespaces to stdout
>
>
```
kubectl cluster-info dump --all-namespaces
```
> Dump a set of namespaces to /path/to/cluster-state
>
>
```
kubectl cluster-info dump --namespaces default,kube-system --output-directory=/path/to/cluster-state
```
Dump cluster information out suitable for debugging and diagnosing cluster problems. By default, dumps everything to stdout. You can optionally specify a directory with --output-directory. If you specify a directory, Kubernetes will build a set of files in that directory. By default, only dumps things in the current namespace and 'kube-system' namespace, but you can switch to a different namespace with the --namespaces flag, or specify --all-namespaces to dump all namespaces.
The command also dumps the logs of all of the pods in the cluster; these logs are dumped into different directories based on namespace and pod name.
### Usage
`$ kubectl cluster-info dump`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all-namespaces | A | false | If true, dump all namespaces. If true, --namespaces is ignored. |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| namespaces | | [] | A comma separated list of namespaces to dump. |
| output | o | json | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| output-directory | | | Where to output the files. If empty or '-' uses stdout, otherwise creates a directory hierarchy in that directory |
| pod-running-timeout | | 20s | The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
cordon
======
> Mark node "foo" as unschedulable
>
>
```
kubectl cordon foo
```
Mark node as unschedulable.
### Usage
`$ kubectl cordon NODE`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
---
drain
=====
> Drain node "foo", even if there are pods not managed by a replication controller, replica set, job, daemon set or stateful set on it
>
>
```
kubectl drain foo --force
```
> As above, but abort if there are pods not managed by a replication controller, replica set, job, daemon set or stateful set, and use a grace period of 15 minutes
>
>
```
kubectl drain foo --grace-period=900
```
Drain node in preparation for maintenance.
The given node will be marked unschedulable to prevent new pods from arriving. 'drain' evicts the pods if the API server supports <https://kubernetes.io/docs/concepts/workloads/pods/disruptions/> . Otherwise, it will use normal DELETE to delete the pods. The 'drain' evicts or deletes all pods except mirror pods (which cannot be deleted through the API server). If there are daemon set-managed pods, drain will not proceed without --ignore-daemonsets, and regardless it will not delete any daemon set-managed pods, because those pods would be immediately replaced by the daemon set controller, which ignores unschedulable markings. If there are any pods that are neither mirror pods nor managed by a replication controller, replica set, daemon set, stateful set, or job, then drain will not delete any pods unless you use --force. --force will also allow deletion to proceed if the managing resource of one or more pods is missing.
'drain' waits for graceful termination. You should not operate on the machine until the command completes.
When you are ready to put the node back into service, use kubectl uncordon, which will make the node schedulable again.
<https://kubernetes.io/images/docs/kubectl_drain.svg>
### Usage
`$ kubectl drain NODE`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| chunk-size | | 500 | Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and may change in the future. |
| delete-emptydir-data | | false | Continue even if there are pods using emptyDir (local data that will be deleted when the node is drained). |
| delete-local-data | | false | Continue even if there are pods using emptyDir (local data that will be deleted when the node is drained). |
| disable-eviction | | false | Force drain to use delete, even if eviction is supported. This will bypass checking PodDisruptionBudgets, use with caution. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| force | | false | Continue even if there are pods that do not declare a controller. |
| grace-period | | -1 | Period of time in seconds given to each pod to terminate gracefully. If negative, the default value specified in the pod will be used. |
| ignore-daemonsets | | false | Ignore DaemonSet-managed pods. |
| pod-selector | | | Label selector to filter pods on the node |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| skip-wait-for-delete-timeout | | 0 | If pod DeletionTimestamp older than N seconds, skip waiting for the pod. Seconds must be greater than 0 to skip. |
| timeout | | 0s | The length of time to wait before giving up, zero means infinite |
---
taint
=====
> Update node 'foo' with a taint with key 'dedicated' and value 'special-user' and effect 'NoSchedule' # If a taint with that key and effect already exists, its value is replaced as specified
>
>
```
kubectl taint nodes foo dedicated=special-user:NoSchedule
```
> Remove from node 'foo' the taint with key 'dedicated' and effect 'NoSchedule' if one exists
>
>
```
kubectl taint nodes foo dedicated:NoSchedule-
```
> Remove from node 'foo' all the taints with key 'dedicated'
>
>
```
kubectl taint nodes foo dedicated-
```
> Add a taint with key 'dedicated' on nodes having label mylabel=X
>
>
```
kubectl taint node -l myLabel=X dedicated=foo:PreferNoSchedule
```
> Add to node 'foo' a taint with key 'bar' and no value
>
>
```
kubectl taint nodes foo bar:NoSchedule
```
Update the taints on one or more nodes.
*A taint consists of a key, value, and effect. As an argument here, it is expressed as key=value:effect.* The key must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to 253 characters.
*Optionally, the key can begin with a DNS subdomain prefix and a single '/', like example.com/my-app.* The value is optional. If given, it must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to 63 characters.
*The effect must be NoSchedule, PreferNoSchedule or NoExecute.* Currently taint can only apply to node.
### Usage
`$ kubectl taint NODE NAME KEY_1=VAL_1:TAINT_EFFECT_1 ... KEY_N=VAL_N:TAINT_EFFECT_N`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all | | false | Select all nodes in the cluster |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| field-manager | | kubectl-taint | Name of the manager used to track field ownership. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| overwrite | | false | If true, allow taints to be overwritten, otherwise reject taint updates that overwrite existing taints. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| validate | | strict | Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields. |
---
uncordon
========
> Mark node "foo" as schedulable
>
>
```
kubectl uncordon foo
```
Mark node as schedulable.
### Usage
`$ kubectl uncordon NODE`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| dry-run | | none | Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. |
| selector | l | | Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints. |
**KUBECTL SETTINGS AND USAGE**
==============================
---
alpha
=====
These commands correspond to alpha features that are not enabled in Kubernetes clusters by default.
### Usage
`$ kubectl alpha`
---
*events*
--------
> List recent events in the default namespace.
>
>
```
kubectl alpha events
```
> List recent events in all namespaces.
>
>
```
kubectl alpha events --all-namespaces
```
> List recent events for the specified pod, then wait for more events and list them as they arrive.
>
>
```
kubectl alpha events --for pod/web-pod-13je7 --watch
```
> List recent events in given format. Supported ones, apart from default, are json and yaml.
>
>
```
kubectl alpha events -oyaml
```
> List recent only events in given event types
>
>
```
kubectl alpha events --types=Warning,Normal
```
Experimental: Display events
Prints a table of the most important information about events. You can request events for a namespace, for all namespace, or filtered to only those pertaining to a specified resource.
### Usage
`$ kubectl alpha events [(-o|--output=)json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file] [--for TYPE/NAME] [--watch] [--event=Normal,Warning]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| all-namespaces | A | false | If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| chunk-size | | 500 | Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and may change in the future. |
| for | | | Filter events to only those pertaining to the specified resource. |
| no-headers | | false | When using the default output format, don't print headers. |
| output | o | | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
| types | | [] | Output only events of given types. |
| watch | w | false | After listing the requested events, watch for more events. |
---
api-resources
=============
> Print the supported API resources
>
>
```
kubectl api-resources
```
> Print the supported API resources with more information
>
>
```
kubectl api-resources -o wide
```
> Print the supported API resources sorted by a column
>
>
```
kubectl api-resources --sort-by=name
```
> Print the supported namespaced resources
>
>
```
kubectl api-resources --namespaced=true
```
> Print the supported non-namespaced resources
>
>
```
kubectl api-resources --namespaced=false
```
> Print the supported API resources with a specific APIGroup
>
>
```
kubectl api-resources --api-group=rbac.authorization.k8s.io
```
Print the supported API resources on the server.
### Usage
`$ kubectl api-resources`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| api-group | | | Limit to resources in the specified API group. |
| cached | | false | Use the cached list of resources if available. |
| namespaced | | true | If false, non-namespaced resources will be returned, otherwise returning namespaced resources by default. |
| no-headers | | false | When using the default or custom-column output format, don't print headers (default print headers). |
| output | o | | Output format. One of: (wide, name). |
| sort-by | | | If non-empty, sort list of resources using specified field. The field can be either 'name' or 'kind'. |
| verbs | | [] | Limit to resources that support the specified verbs. |
---
completion
==========
> Installing bash completion on macOS using homebrew ## If running Bash 3.2 included with macOS
>
>
```
brew install bash-completion
```
> or, if running Bash 4.1+
>
>
```
brew install bash-completion@2
```
> If kubectl is installed via homebrew, this should start working immediately ## If you've installed via other means, you may need add the completion to your completion directory
>
>
```
kubectl completion bash > $(brew --prefix)/etc/bash_completion.d/kubectl
```
> Installing bash completion on Linux ## If bash-completion is not installed on Linux, install the 'bash-completion' package ## via your distribution's package manager. ## Load the kubectl completion code for bash into the current shell
>
>
```
source <(kubectl completion bash)
```
> Write bash completion code to a file and source it from .bash\_profile
>
>
```
kubectl completion bash > ~/.kube/completion.bash.inc printf "
```
> Kubectl shell completion
>
>
```
source '$HOME/.kube/completion.bash.inc' " >> $HOME/.bash_profile source $HOME/.bash_profile
```
> Load the kubectl completion code for zsh[1] into the current shell
>
>
```
source <(kubectl completion zsh)
```
> Set the kubectl completion code for zsh[1] to autoload on startup
>
>
```
kubectl completion zsh > "${fpath[1]}/_kubectl"
```
> Load the kubectl completion code for fish[2] into the current shell
>
>
```
kubectl completion fish | source
```
> To load completions for each session, execute once:
>
>
```
kubectl completion fish > ~/.config/fish/completions/kubectl.fish
```
> Load the kubectl completion code for powershell into the current shell
>
>
```
kubectl completion powershell | Out-String | Invoke-Expression
```
> Set kubectl completion code for powershell to run on startup ## Save completion code to a script and execute in the profile
>
>
```
kubectl completion powershell > $HOME\.kube\completion.ps1 Add-Content $PROFILE "$HOME\.kube\completion.ps1"
```
> Execute completion code in the profile
>
>
```
Add-Content $PROFILE "if (Get-Command kubectl -ErrorAction SilentlyContinue) { kubectl completion powershell | Out-String | Invoke-Expression }"
```
> Add completion code directly to the $PROFILE script
>
>
```
kubectl completion powershell >> $PROFILE
```
Output shell completion code for the specified shell (bash, zsh, fish, or powershell). The shell code must be evaluated to provide interactive completion of kubectl commands. This can be done by sourcing it from the .bash\_profile.
Detailed instructions on how to do this are available here:
for macOS:
<https://kubernetes.io/docs/tasks/tools/install-kubectl-macos/#enable-shell-autocompletion>
for linux:
<https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/#enable-shell-autocompletion>
for windows:
<https://kubernetes.io/docs/tasks/tools/install-kubectl-windows/#enable-shell-autocompletion>
Note for zsh users: [1] zsh completions are only supported in versions of zsh >= 5.2.
### Usage
`$ kubectl completion SHELL`
---
config
======
Modify kubeconfig files using subcommands like "kubectl config set current-context my-context"
The loading order follows these rules:
1. If the --kubeconfig flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.
2. If $KUBECONFIG environment variable is set, then it is used as a list of paths (normal path delimiting rules for your system). These paths are merged. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list.
3. Otherwise, ${HOME}/.kube/config is used and no merging takes place.
### Usage
`$ kubectl config SUBCOMMAND`
---
*current-context*
-----------------
> Display the current-context
>
>
```
kubectl config current-context
```
Display the current-context.
### Usage
`$ kubectl config current-context`
---
*delete-cluster*
----------------
> Delete the minikube cluster
>
>
```
kubectl config delete-cluster minikube
```
Delete the specified cluster from the kubeconfig.
### Usage
`$ kubectl config delete-cluster NAME`
---
*delete-context*
----------------
> Delete the context for the minikube cluster
>
>
```
kubectl config delete-context minikube
```
Delete the specified context from the kubeconfig.
### Usage
`$ kubectl config delete-context NAME`
---
*delete-user*
-------------
> Delete the minikube user
>
>
```
kubectl config delete-user minikube
```
Delete the specified user from the kubeconfig.
### Usage
`$ kubectl config delete-user NAME`
---
*get-clusters*
--------------
> List the clusters that kubectl knows about
>
>
```
kubectl config get-clusters
```
Display clusters defined in the kubeconfig.
### Usage
`$ kubectl config get-clusters`
---
*get-contexts*
--------------
> List all the contexts in your kubeconfig file
>
>
```
kubectl config get-contexts
```
> Describe one context in your kubeconfig file
>
>
```
kubectl config get-contexts my-context
```
Display one or many contexts from the kubeconfig file.
### Usage
`$ kubectl config get-contexts [(-o|--output=)name)]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| no-headers | | false | When using the default or custom-column output format, don't print headers (default print headers). |
| output | o | | Output format. One of: (name). |
---
*get-users*
-----------
> List the users that kubectl knows about
>
>
```
kubectl config get-users
```
Display users defined in the kubeconfig.
### Usage
`$ kubectl config get-users`
---
*rename-context*
----------------
> Rename the context 'old-name' to 'new-name' in your kubeconfig file
>
>
```
kubectl config rename-context old-name new-name
```
Renames a context from the kubeconfig file.
CONTEXT\_NAME is the context name that you want to change.
NEW\_NAME is the new name you want to set.
Note: If the context being renamed is the 'current-context', this field will also be updated.
### Usage
`$ kubectl config rename-context CONTEXT_NAME NEW_NAME`
---
*set*
-----
> Set the server field on the my-cluster cluster to <https://1.2.3.4>
>
>
```
kubectl config set clusters.my-cluster.server https://1.2.3.4
```
> Set the certificate-authority-data field on the my-cluster cluster
>
>
```
kubectl config set clusters.my-cluster.certificate-authority-data $(echo "cert_data_here" | base64 -i -)
```
> Set the cluster field in the my-context context to my-cluster
>
>
```
kubectl config set contexts.my-context.cluster my-cluster
```
> Set the client-key-data field in the cluster-admin user using --set-raw-bytes option
>
>
```
kubectl config set users.cluster-admin.client-key-data cert_data_here --set-raw-bytes=true
```
Set an individual value in a kubeconfig file.
PROPERTY\_NAME is a dot delimited name where each token represents either an attribute name or a map key. Map keys may not contain dots.
PROPERTY\_VALUE is the new value you want to set. Binary fields such as 'certificate-authority-data' expect a base64 encoded string unless the --set-raw-bytes flag is used.
Specifying an attribute name that already exists will merge new fields on top of existing values.
### Usage
`$ kubectl config set PROPERTY_NAME PROPERTY_VALUE`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| set-raw-bytes | | false | When writing a []byte PROPERTY\_VALUE, write the given string directly without base64 decoding. |
---
*set-cluster*
-------------
> Set only the server field on the e2e cluster entry without touching other values
>
>
```
kubectl config set-cluster e2e --server=https://1.2.3.4
```
> Embed certificate authority data for the e2e cluster entry
>
>
```
kubectl config set-cluster e2e --embed-certs --certificate-authority=~/.kube/e2e/kubernetes.ca.crt
```
> Disable cert checking for the e2e cluster entry
>
>
```
kubectl config set-cluster e2e --insecure-skip-tls-verify=true
```
> Set custom TLS server name to use for validation for the e2e cluster entry
>
>
```
kubectl config set-cluster e2e --tls-server-name=my-cluster-name
```
> Set proxy url for the e2e cluster entry
>
>
```
kubectl config set-cluster e2e --proxy-url=https://1.2.3.4
```
Set a cluster entry in kubeconfig.
Specifying a name that already exists will merge new fields on top of existing values for those fields.
### Usage
`$ kubectl config set-cluster NAME [--server=server] [--certificate-authority=path/to/certificate/authority] [--insecure-skip-tls-verify=true] [--tls-server-name=example.com]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| embed-certs | | false | embed-certs for the cluster entry in kubeconfig |
| proxy-url | | | proxy-url for the cluster entry in kubeconfig |
---
*set-context*
-------------
> Set the user field on the gce context entry without touching other values
>
>
```
kubectl config set-context gce --user=cluster-admin
```
Set a context entry in kubeconfig.
Specifying a name that already exists will merge new fields on top of existing values for those fields.
### Usage
`$ kubectl config set-context [NAME | --current] [--cluster=cluster_nickname] [--user=user_nickname] [--namespace=namespace]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| current | | false | Modify the current context |
---
*set-credentials*
-----------------
> Set only the "client-key" field on the "cluster-admin" # entry, without touching other values
>
>
```
kubectl config set-credentials cluster-admin --client-key=~/.kube/admin.key
```
> Set basic auth for the "cluster-admin" entry
>
>
```
kubectl config set-credentials cluster-admin --username=admin --password=uXFGweU9l35qcif
```
> Embed client certificate data in the "cluster-admin" entry
>
>
```
kubectl config set-credentials cluster-admin --client-certificate=~/.kube/admin.crt --embed-certs=true
```
> Enable the Google Compute Platform auth provider for the "cluster-admin" entry
>
>
```
kubectl config set-credentials cluster-admin --auth-provider=gcp
```
> Enable the OpenID Connect auth provider for the "cluster-admin" entry with additional args
>
>
```
kubectl config set-credentials cluster-admin --auth-provider=oidc --auth-provider-arg=client-id=foo --auth-provider-arg=client-secret=bar
```
> Remove the "client-secret" config value for the OpenID Connect auth provider for the "cluster-admin" entry
>
>
```
kubectl config set-credentials cluster-admin --auth-provider=oidc --auth-provider-arg=client-secret-
```
> Enable new exec auth plugin for the "cluster-admin" entry
>
>
```
kubectl config set-credentials cluster-admin --exec-command=/path/to/the/executable --exec-api-version=client.authentication.k8s.io/v1beta1
```
> Define new exec auth plugin args for the "cluster-admin" entry
>
>
```
kubectl config set-credentials cluster-admin --exec-arg=arg1 --exec-arg=arg2
```
> Create or update exec auth plugin environment variables for the "cluster-admin" entry
>
>
```
kubectl config set-credentials cluster-admin --exec-env=key1=val1 --exec-env=key2=val2
```
> Remove exec auth plugin environment variables for the "cluster-admin" entry
>
>
```
kubectl config set-credentials cluster-admin --exec-env=var-to-remove-
```
Set a user entry in kubeconfig.
Specifying a name that already exists will merge new fields on top of existing values.
Client-certificate flags: --client-certificate=certfile --client-key=keyfile
Bearer token flags: --token=bearer\_token
Basic auth flags: --username=basic\_user --password=basic\_password
Bearer token and basic auth are mutually exclusive.
### Usage
`$ kubectl config set-credentials NAME [--client-certificate=path/to/certfile] [--client-key=path/to/keyfile] [--token=bearer_token] [--username=basic_user] [--password=basic_password] [--auth-provider=provider_name] [--auth-provider-arg=key=value] [--exec-command=exec_command] [--exec-api-version=exec_api_version] [--exec-arg=arg] [--exec-env=key=value]`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| auth-provider | | | Auth provider for the user entry in kubeconfig |
| auth-provider-arg | | [] | 'key=value' arguments for the auth provider |
| embed-certs | | false | Embed client cert/key for the user entry in kubeconfig |
| exec-api-version | | | API version of the exec credential plugin for the user entry in kubeconfig |
| exec-arg | | [] | New arguments for the exec credential plugin command for the user entry in kubeconfig |
| exec-command | | | Command for the exec credential plugin for the user entry in kubeconfig |
| exec-env | | [] | 'key=value' environment values for the exec credential plugin |
---
*unset*
-------
> Unset the current-context
>
>
```
kubectl config unset current-context
```
> Unset namespace in foo context
>
>
```
kubectl config unset contexts.foo.namespace
```
Unset an individual value in a kubeconfig file.
PROPERTY\_NAME is a dot delimited name where each token represents either an attribute name or a map key. Map keys may not contain dots.
### Usage
`$ kubectl config unset PROPERTY_NAME`
---
*use-context*
-------------
> Use the context for the minikube cluster
>
>
```
kubectl config use-context minikube
```
Set the current-context in a kubeconfig file.
### Usage
`$ kubectl config use-context CONTEXT_NAME`
---
*view*
------
> Show merged kubeconfig settings
>
>
```
kubectl config view
```
> Show merged kubeconfig settings and raw certificate data
>
>
```
kubectl config view --raw
```
> Get the password for the e2e user
>
>
```
kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'
```
Display merged kubeconfig settings or a specified kubeconfig file.
You can use --output jsonpath={...} to extract specific values using a jsonpath expression.
### Usage
`$ kubectl config view`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| allow-missing-template-keys | | true | If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. |
| flatten | | false | Flatten the resulting kubeconfig file into self-contained output (useful for creating portable kubeconfig files) |
| merge | | true | Merge the full hierarchy of kubeconfig files |
| minify | | false | Remove all information not used by current-context from the output |
| output | o | yaml | Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). |
| raw | | false | Display raw byte data |
| show-managed-fields | | false | If true, keep the managedFields when printing objects in JSON or YAML format. |
| template | | | Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [<http://golang.org/pkg/text/template/#pkg-overview>]. |
---
explain
=======
> Get the documentation of the resource and its fields
>
>
```
kubectl explain pods
```
> Get the documentation of a specific field of a resource
>
>
```
kubectl explain pods.spec.containers
```
List the fields for supported resources.
This command describes the fields associated with each supported API resource. Fields are identified via a simple JSONPath identifier:
<type>.<fieldName>[.<fieldName>]
Add the --recursive flag to display all of the fields at once without descriptions. Information about each field is retrieved from the server in OpenAPI format.
Use "kubectl api-resources" for a complete list of supported resources.
### Usage
`$ kubectl explain RESOURCE`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| api-version | | | Get different explanations for particular API version (API group/version) |
| recursive | | false | Print the fields of fields (Currently only 1 level deep) |
---
options
=======
> Print flags inherited by all commands
>
>
```
kubectl options
```
Print the list of flags inherited by all commands
### Usage
`$ kubectl options`
---
plugin
======
Provides utilities for interacting with plugins.
Plugins provide extended functionality that is not part of the major command-line distribution. Please refer to the documentation and examples for more information about how write your own plugins.
The easiest way to discover and install plugins is via the kubernetes sub-project krew. To install krew, visit <https://krew.sigs.k8s.io/docs/user-guide/setup/install/>
### Usage
`$ kubectl plugin [flags]`
---
*list*
------
> List all available plugins
>
>
```
kubectl plugin list
```
List all available plugin files on a user's PATH.
Available plugin files are those that are: - executable - anywhere on the user's PATH - begin with "kubectl-"
### Usage
`$ kubectl plugin list`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| name-only | | false | If true, display only the binary name of each plugin, rather than its full path |
---
version
=======
> Print the client and server versions for the current context
>
>
```
kubectl version
```
Print the client and server version information for the current context.
### Usage
`$ kubectl version`
### Flags
| Name | Shorthand | Default | Usage |
| --- | --- | --- | --- |
| client | | false | If true, shows client version only (no server required). |
| output | o | | One of 'yaml' or 'json'. |
| short | | false | If true, print just the version number. |
| programming_docs |
express Express Express
=======
express()
---------
Creates an Express application. The `express()` function is a top-level function exported by the `express` module.
```
var express = require('express')
var app = express()
```
### Methods
### express.json([options])
This middleware is available in Express v4.16.0 onwards.
This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on [body-parser](https://expressjs.com/resources/middleware/body-parser.html).
Returns middleware that only parses JSON and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts any Unicode encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings.
A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`), or an empty object (`{}`) if there was no body to parse, the `Content-Type` was not matched, or an error occurred.
As `req.body`’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input.
The following table describes the properties of the optional `options` object.
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` |
| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `"100kb"` |
| `reviver` | The `reviver` option is passed directly to `JSON.parse` as the second argument. You can find more information on this argument [in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). | Function | `null` |
| `strict` | Enables or disables only accepting arrays and objects; when disabled will accept anything `JSON.parse` accepts. | Boolean | `true` |
| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `json`), a mime type (like `application/json`), or a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `"application/json"` |
| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` |
### express.raw([options])
This middleware is available in Express v4.17.0 onwards.
This is a built-in middleware function in Express. It parses incoming request payloads into a `Buffer` and is based on [body-parser](https://expressjs.com/resources/middleware/body-parser.html).
Returns middleware that parses all bodies as a `Buffer` and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts any Unicode encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings.
A new `body` `Buffer` containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`), or an empty object (`{}`) if there was no body to parse, the `Content-Type` was not matched, or an error occurred.
As `req.body`’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.toString()` may fail in multiple ways, for example stacking multiple parsers `req.body` may be from a different parser. Testing that `req.body` is a `Buffer` before calling buffer methods is recommended.
The following table describes the properties of the optional `options` object.
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` |
| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `"100kb"` |
| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `bin`), a mime type (like `application/octet-stream`), or a mime type with a wildcard (like `*/*` or `application/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `"application/octet-stream"` |
| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` |
### express.Router([options])
Creates a new [router](#router) object.
```
var router = express.Router([options])
```
The optional `options` parameter specifies the behavior of the router.
| Property | Description | Default | Availability |
| --- | --- | --- | --- |
| `caseSensitive` | Enable case sensitivity. | Disabled by default, treating “/Foo” and “/foo” as the same. | |
| `mergeParams` | Preserve the `req.params` values from the parent router. If the parent and the child have conflicting param names, the child’s value take precedence. | `false` | 4.5.0+ |
| `strict` | Enable strict routing. | Disabled by default, “/foo” and “/foo/” are treated the same by the router. | |
You can add middleware and HTTP method routes (such as `get`, `put`, `post`, and so on) to `router` just like an application.
For more information, see [Router](#router).
### express.static(root, [options])
This is a built-in middleware function in Express. It serves static files and is based on [serve-static](https://expressjs.com/resources/middleware/serve-static.html).
NOTE: For best results, [use a reverse proxy](advanced/best-practice-performance#use-a-reverse-proxy) cache to improve performance of serving static assets.
The `root` argument specifies the root directory from which to serve static assets. The function determines the file to serve by combining `req.url` with the provided `root` directory. When a file is not found, instead of sending a 404 response, it calls `next()` to move on to the next middleware, allowing for stacking and fall-backs.
The following table describes the properties of the `options` object. See also the [example below](#example.of.express.static).
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| `dotfiles` | Determines how dotfiles (files or directories that begin with a dot “.”) are treated. See [dotfiles](#dotfiles) below. | String | “ignore” |
| `etag` | Enable or disable etag generation NOTE: `express.static` always sends weak ETags. | Boolean | `true` |
| `extensions` | Sets file extension fallbacks: If a file is not found, search for files with the specified extensions and serve the first one found. Example: `['html', 'htm']`. | Mixed | `false` |
| `fallthrough` | Let client errors fall-through as unhandled requests, otherwise forward a client error. See [fallthrough](#fallthrough) below. | Boolean | `true` |
| `immutable` | Enable or disable the `immutable` directive in the `Cache-Control` response header. If enabled, the `maxAge` option should also be specified to enable caching. The `immutable` directive will prevent supported clients from making conditional requests during the life of the `maxAge` option to check if the file has changed. | Boolean | `false` |
| `index` | Sends the specified directory index file. Set to `false` to disable directory indexing. | Mixed | “index.html” |
| `lastModified` | Set the `Last-Modified` header to the last modified date of the file on the OS. | Boolean | `true` |
| `maxAge` | Set the max-age property of the Cache-Control header in milliseconds or a string in [ms format](https://www.npmjs.org/package/ms). | Number | 0 |
| `redirect` | Redirect to trailing “/” when the pathname is a directory. | Boolean | `true` |
| `setHeaders` | Function for setting HTTP headers to serve with the file. See [setHeaders](#setHeaders) below. | Function | |
For more information, see [Serving static files in Express](https://expressjs.com/starter/static-files.html). and [Using middleware - Built-in middleware](guide/using-middleware#middleware.built-in).
##### dotfiles
Possible values for this option are:
* “allow” - No special treatment for dotfiles.
* “deny” - Deny a request for a dotfile, respond with `403`, then call `next()`.
* “ignore” - Act as if the dotfile does not exist, respond with `404`, then call `next()`.
**NOTE**: With the default value, it will not ignore files in a directory that begins with a dot.
##### fallthrough
When this option is `true`, client errors such as a bad request or a request to a non-existent file will cause this middleware to simply call `next()` to invoke the next middleware in the stack. When false, these errors (even 404s), will invoke `next(err)`.
Set this option to `true` so you can map multiple physical directories to the same web address or for routes to fill in non-existent files.
Use `false` if you have mounted this middleware at a path designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods.
##### setHeaders
For this option, specify a function to set custom response headers. Alterations to the headers must occur synchronously.
The signature of the function is:
```
fn(res, path, stat)
```
Arguments:
* `res`, the [response object](#res).
* `path`, the file path that is being sent.
* `stat`, the `stat` object of the file that is being sent.
#### Example of express.static
Here is an example of using the `express.static` middleware function with an elaborate options object:
```
var options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now())
}
}
app.use(express.static('public', options))
```
### express.text([options])
This middleware is available in Express v4.17.0 onwards.
This is a built-in middleware function in Express. It parses incoming request payloads into a string and is based on [body-parser](https://expressjs.com/resources/middleware/body-parser.html).
Returns middleware that parses all bodies as a string and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts any Unicode encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings.
A new `body` string containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`), or an empty object (`{}`) if there was no body to parse, the `Content-Type` was not matched, or an error occurred.
As `req.body`’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.trim()` may fail in multiple ways, for example stacking multiple parsers `req.body` may be from a different parser. Testing that `req.body` is a string before calling string methods is recommended.
The following table describes the properties of the optional `options` object.
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| `defaultCharset` | Specify the default character set for the text content if the charset is not specified in the `Content-Type` header of the request. | String | `"utf-8"` |
| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` |
| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `"100kb"` |
| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `txt`), a mime type (like `text/plain`), or a mime type with a wildcard (like `*/*` or `text/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `"text/plain"` |
| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` |
### express.urlencoded([options])
This middleware is available in Express v4.16.0 onwards.
This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on [body-parser](https://expressjs.com/resources/middleware/body-parser.html).
Returns middleware that only parses urlencoded bodies and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings.
A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`), or an empty object (`{}`) if there was no body to parse, the `Content-Type` was not matched, or an error occurred. This object will contain key-value pairs, where the value can be a string or array (when `extended` is `false`), or any type (when `extended` is `true`).
As `req.body`’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input.
The following table describes the properties of the optional `options` object.
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| `extended` | This option allows to choose between parsing the URL-encoded data with the `querystring` library (when `false`) or the `qs` library (when `true`). The “extended” syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please [see the qs library](https://www.npmjs.org/package/qs#readme). | Boolean | `true` |
| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` |
| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `"100kb"` |
| `parameterLimit` | This option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, an error will be raised. | Number | `1000` |
| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `urlencoded`), a mime type (like `application/x-www-form-urlencoded`), or a mime type with a wildcard (like `*/x-www-form-urlencoded`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `"application/x-www-form-urlencoded"` |
| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` |
Application
-----------
The `app` object conventionally denotes the Express application. Create it by calling the top-level `express()` function exported by the Express module:
```
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('hello world')
})
app.listen(3000)
```
The `app` object has methods for
* Routing HTTP requests; see for example, [app.METHOD](#app.METHOD) and [app.param](#app.param).
* Configuring middleware; see [app.route](#app.route).
* Rendering HTML views; see [app.render](#app.render).
* Registering a template engine; see [app.engine](#app.engine).
It also has settings (properties) that affect how the application behaves; for more information, see [Application settings](#app.settings.table).
The Express application object can be referred from the [request object](#req) and the [response object](#res) as `req.app`, and `res.app`, respectively.
### Properties
### app.locals
The `app.locals` object has properties that are local variables within the application, and will be available in templates rendered with [res.render](#res.render).
```
console.dir(app.locals.title)
// => 'My App'
console.dir(app.locals.email)
// => '[email protected]'
```
Once set, the value of `app.locals` properties persist throughout the life of the application, in contrast with [res.locals](#res.locals) properties that are valid only for the lifetime of the request.
You can access local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as application-level data. Local variables are available in middleware via `req.app.locals` (see [req.app](#req.app))
```
app.locals.title = 'My App'
app.locals.strftime = require('strftime')
app.locals.email = '[email protected]'
```
### app.mountpath
The `app.mountpath` property contains one or more path patterns on which a sub-app was mounted.
A sub-app is an instance of `express` that may be used for handling the request to a route.
```
var express = require('express')
var app = express() // the main app
var admin = express() // the sub app
admin.get('/', function (req, res) {
console.log(admin.mountpath) // /admin
res.send('Admin Homepage')
})
app.use('/admin', admin) // mount the sub app
```
It is similar to the [baseUrl](#req.baseUrl) property of the `req` object, except `req.baseUrl` returns the matched URL path, instead of the matched patterns.
If a sub-app is mounted on multiple path patterns, `app.mountpath` returns the list of patterns it is mounted on, as shown in the following example.
```
var admin = express()
admin.get('/', function (req, res) {
console.dir(admin.mountpath) // [ '/adm*n', '/manager' ]
res.send('Admin Homepage')
})
var secret = express()
secret.get('/', function (req, res) {
console.log(secret.mountpath) // /secr*t
res.send('Admin Secret')
})
admin.use('/secr*t', secret) // load the 'secret' router on '/secr*t', on the 'admin' sub app
app.use(['/adm*n', '/manager'], admin) // load the 'admin' router on '/adm*n' and '/manager', on the parent app
```
### Events
### app.on('mount', callback(parent))
The `mount` event is fired on a sub-app, when it is mounted on a parent app. The parent app is passed to the callback function.
**NOTE**
Sub-apps will:
* Not inherit the value of settings that have a default value. You must set the value in the sub-app.
* Inherit the value of settings with no default value.
For details, see [Application settings](index#app.settings.table).
```
var admin = express()
admin.on('mount', function (parent) {
console.log('Admin Mounted')
console.log(parent) // refers to the parent app
})
admin.get('/', function (req, res) {
res.send('Admin Homepage')
})
app.use('/admin', admin)
```
### Methods
### app.all(path, callback [, callback ...])
This method is like the standard [app.METHOD()](#app.METHOD) methods, except it matches all HTTP verbs.
#### Arguments
| Argument | Description | Default |
| --- | --- | --- |
| `path` | The path for which the middleware function is invoked; can be any of: * A string representing a path.
* A path pattern.
* A regular expression pattern to match paths.
* An array of combinations of any of the above.
For examples, see [Path examples](#path-examples). | '/' (root path) |
| `callback` | Callback functions; can be: * A middleware function.
* A series of middleware functions (separated by commas).
* An array of middleware functions.
* A combination of all of the above.
You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.
Since [router](#router) and [app](#application) implement the middleware interface, you can use them as you would any other middleware function.
For examples, see [Middleware callback function examples](#middleware-callback-function-examples). | None |
#### Examples
The following callback is executed for requests to `/secret` whether using GET, POST, PUT, DELETE, or any other HTTP request method:
```
app.all('/secret', function (req, res, next) {
console.log('Accessing the secret section ...')
next() // pass control to the next handler
})
```
The `app.all()` method is useful for mapping “global” logic for specific path prefixes or arbitrary matches. For example, if you put the following at the top of all other route definitions, it requires that all routes from that point on require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end-points: `loadUser` can perform a task, then call `next()` to continue matching subsequent routes.
```
app.all('*', requireAuthentication, loadUser)
```
Or the equivalent:
```
app.all('*', requireAuthentication)
app.all('*', loadUser)
```
Another example is white-listed “global” functionality. The example is similar to the ones above, but it only restricts paths that start with “/api”:
```
app.all('/api/*', requireAuthentication)
```
### app.delete(path, callback [, callback ...])
Routes HTTP DELETE requests to the specified path with the specified callback functions. For more information, see the [routing guide](https://expressjs.com/guide/routing.html).
#### Arguments
| Argument | Description | Default |
| --- | --- | --- |
| `path` | The path for which the middleware function is invoked; can be any of: * A string representing a path.
* A path pattern.
* A regular expression pattern to match paths.
* An array of combinations of any of the above.
For examples, see [Path examples](#path-examples). | '/' (root path) |
| `callback` | Callback functions; can be: * A middleware function.
* A series of middleware functions (separated by commas).
* An array of middleware functions.
* A combination of all of the above.
You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.
Since [router](#router) and [app](#application) implement the middleware interface, you can use them as you would any other middleware function.
For examples, see [Middleware callback function examples](#middleware-callback-function-examples). | None |
#### Example
```
app.delete('/', function (req, res) {
res.send('DELETE request to homepage')
})
```
### app.disable(name)
Sets the Boolean setting `name` to `false`, where `name` is one of the properties from the [app settings table](#app.settings.table). Calling `app.set('foo', false)` for a Boolean property is the same as calling `app.disable('foo')`.
For example:
```
app.disable('trust proxy')
app.get('trust proxy')
// => false
```
### app.disabled(name)
Returns `true` if the Boolean setting `name` is disabled (`false`), where `name` is one of the properties from the [app settings table](#app.settings.table).
```
app.disabled('trust proxy')
// => true
app.enable('trust proxy')
app.disabled('trust proxy')
// => false
```
### app.enable(name)
Sets the Boolean setting `name` to `true`, where `name` is one of the properties from the [app settings table](#app.settings.table). Calling `app.set('foo', true)` for a Boolean property is the same as calling `app.enable('foo')`.
```
app.enable('trust proxy')
app.get('trust proxy')
// => true
```
### app.enabled(name)
Returns `true` if the setting `name` is enabled (`true`), where `name` is one of the properties from the [app settings table](#app.settings.table).
```
app.enabled('trust proxy')
// => false
app.enable('trust proxy')
app.enabled('trust proxy')
// => true
```
### app.engine(ext, callback)
Registers the given template engine `callback` as `ext`.
By default, Express will `require()` the engine based on the file extension. For example, if you try to render a “foo.pug” file, Express invokes the following internally, and caches the `require()` on subsequent calls to increase performance.
```
app.engine('pug', require('pug').__express)
```
Use this method for engines that do not provide `.__express` out of the box, or if you wish to “map” a different extension to the template engine.
For example, to map the EJS template engine to “.html” files:
```
app.engine('html', require('ejs').renderFile)
```
In this case, EJS provides a `.renderFile()` method with the same signature that Express expects: `(path, options, callback)`, though note that it aliases this method as `ejs.__express` internally so if you’re using “.ejs” extensions you don’t need to do anything.
Some template engines do not follow this convention. The [consolidate.js](https://github.com/tj/consolidate.js) library maps Node template engines to follow this convention, so they work seamlessly with Express.
```
var engines = require('consolidate')
app.engine('haml', engines.haml)
app.engine('html', engines.hogan)
```
### app.get(name)
Returns the value of `name` app setting, where `name` is one of the strings in the [app settings table](#app.settings.table). For example:
```
app.get('title')
// => undefined
app.set('title', 'My Site')
app.get('title')
// => "My Site"
```
### app.get(path, callback [, callback ...])
Routes HTTP GET requests to the specified path with the specified callback functions.
#### Arguments
| Argument | Description | Default |
| --- | --- | --- |
| `path` | The path for which the middleware function is invoked; can be any of: * A string representing a path.
* A path pattern.
* A regular expression pattern to match paths.
* An array of combinations of any of the above.
For examples, see [Path examples](#path-examples). | '/' (root path) |
| `callback` | Callback functions; can be: * A middleware function.
* A series of middleware functions (separated by commas).
* An array of middleware functions.
* A combination of all of the above.
You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.
Since [router](#router) and [app](#application) implement the middleware interface, you can use them as you would any other middleware function.
For examples, see [Middleware callback function examples](#middleware-callback-function-examples). | None |
For more information, see the [routing guide](https://expressjs.com/guide/routing.html).
#### Example
```
app.get('/', function (req, res) {
res.send('GET request to homepage')
})
```
### app.listen(path, [callback])
Starts a UNIX socket and listens for connections on the given path. This method is identical to Node’s [http.Server.listen()](https://nodejs.org/api/http.html#http_server_listen).
```
var express = require('express')
var app = express()
app.listen('/tmp/sock')
```
### app.listen([port[, host[, backlog]]][, callback])
Binds and listens for connections on the specified host and port. This method is identical to Node’s [http.Server.listen()](https://nodejs.org/api/http.html#http_server_listen).
If port is omitted or is 0, the operating system will assign an arbitrary unused port, which is useful for cases like automated tasks (tests, etc.).
```
var express = require('express')
var app = express()
app.listen(3000)
```
The `app` returned by `express()` is in fact a JavaScript `Function`, designed to be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):
```
var express = require('express')
var https = require('https')
var http = require('http')
var app = express()
http.createServer(app).listen(80)
https.createServer(options, app).listen(443)
```
The `app.listen()` method returns an [http.Server](https://nodejs.org/api/http.html#http_class_http_server) object and (for HTTP) is a convenience method for the following:
```
app.listen = function () {
var server = http.createServer(this)
return server.listen.apply(server, arguments)
}
```
NOTE: All the forms of Node’s [http.Server.listen()](https://nodejs.org/api/http.html#http_server_listen) method are in fact actually supported.
### app.METHOD(path, callback [, callback ...])
Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are `app.get()`, `app.post()`, `app.put()`, and so on. See [Routing methods](#routing-methods) below for the complete list.
#### Arguments
| Argument | Description | Default |
| --- | --- | --- |
| `path` | The path for which the middleware function is invoked; can be any of: * A string representing a path.
* A path pattern.
* A regular expression pattern to match paths.
* An array of combinations of any of the above.
For examples, see [Path examples](#path-examples). | '/' (root path) |
| `callback` | Callback functions; can be: * A middleware function.
* A series of middleware functions (separated by commas).
* An array of middleware functions.
* A combination of all of the above.
You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.
Since [router](#router) and [app](#application) implement the middleware interface, you can use them as you would any other middleware function.
For examples, see [Middleware callback function examples](#middleware-callback-function-examples). | None |
#### Routing methods
Express supports the following routing methods corresponding to the HTTP methods of the same names:
| | | |
| --- | --- | --- |
| * `checkout`
* `copy`
* `delete`
* `get`
* `head`
* `lock`
* `merge`
* `mkactivity`
| * `mkcol`
* `move`
* `m-search`
* `notify`
* `options`
* `patch`
* `post`
| * `purge`
* `put`
* `report`
* `search`
* `subscribe`
* `trace`
* `unlock`
* `unsubscribe`
|
The API documentation has explicit entries only for the most popular HTTP methods `app.get()`, `app.post()`, `app.put()`, and `app.delete()`. However, the other methods listed above work in exactly the same way.
To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, `app['m-search']('/', function ...`.
The `app.get()` function is automatically called for the HTTP `HEAD` method in addition to the `GET` method if `app.head()` was not called for the path before `app.get()`.
The method, `app.all()`, is not derived from any HTTP method and loads middleware at the specified path for *all* HTTP request methods. For more information, see [app.all](#app.all).
For more information on routing, see the [routing guide](https://expressjs.com/guide/routing.html).
### app.param([name], callback)
Add callback triggers to [route parameters](guide/routing#route-parameters), where `name` is the name of the parameter or an array of them, and `callback` is the callback function. The parameters of the callback function are the request object, the response object, the next middleware, the value of the parameter and the name of the parameter, in that order.
If `name` is an array, the `callback` trigger is registered for each parameter declared in it, in the order in which they are declared. Furthermore, for each declared parameter except the last one, a call to `next` inside the callback will call the callback for the next declared parameter. For the last parameter, a call to `next` will call the next middleware in place for the route currently being processed, just like it would if `name` were just a string.
For example, when `:user` is present in a route path, you may map user loading logic to automatically provide `req.user` to the route, or perform validations on the parameter input.
```
app.param('user', function (req, res, next, id) {
// try to get the user details from the User model and attach it to the request object
User.find(id, function (err, user) {
if (err) {
next(err)
} else if (user) {
req.user = user
next()
} else {
next(new Error('failed to load user'))
}
})
})
```
Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers. Hence, param callbacks defined on `app` will be triggered only by route parameters defined on `app` routes.
All param callbacks will be called before any handler of any route in which the param occurs, and they will each be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.
```
app.param('id', function (req, res, next, id) {
console.log('CALLED ONLY ONCE')
next()
})
app.get('/user/:id', function (req, res, next) {
console.log('although this matches')
next()
})
app.get('/user/:id', function (req, res) {
console.log('and this matches too')
res.end()
})
```
On `GET /user/42`, the following is printed:
```
CALLED ONLY ONCE
although this matches
and this matches too
```
```
app.param(['id', 'page'], function (req, res, next, value) {
console.log('CALLED ONLY ONCE with', value)
next()
})
app.get('/user/:id/:page', function (req, res, next) {
console.log('although this matches')
next()
})
app.get('/user/:id/:page', function (req, res) {
console.log('and this matches too')
res.end()
})
```
On `GET /user/42/3`, the following is printed:
```
CALLED ONLY ONCE with 42
CALLED ONLY ONCE with 3
although this matches
and this matches too
```
The following section describes `app.param(callback)`, which is deprecated as of v4.11.0.
The behavior of the `app.param(name, callback)` method can be altered entirely by passing only a function to `app.param()`. This function is a custom implementation of how `app.param(name, callback)` should behave - it accepts two parameters and must return a middleware.
The first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation.
The middleware returned by the function decides the behavior of what happens when a URL parameter is captured.
In this example, the `app.param(name, callback)` signature is modified to `app.param(name, accessId)`. Instead of accepting a name and a callback, `app.param()` will now accept a name and a number.
```
var express = require('express')
var app = express()
// customizing the behavior of app.param()
app.param(function (param, option) {
return function (req, res, next, val) {
if (val === option) {
next()
} else {
next('route')
}
}
})
// using the customized app.param()
app.param('id', 1337)
// route to trigger the capture
app.get('/user/:id', function (req, res) {
res.send('OK')
})
app.listen(3000, function () {
console.log('Ready')
})
```
In this example, the `app.param(name, callback)` signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id.
```
app.param(function (param, validator) {
return function (req, res, next, val) {
if (validator(val)) {
next()
} else {
next('route')
}
}
})
app.param('id', function (candidate) {
return !isNaN(parseFloat(candidate)) && isFinite(candidate)
})
```
The ‘`.`’ character can’t be used to capture a character in your capturing regexp. For example you can’t use `'/user-.+/'` to capture `'users-gami'`, use `[\\s\\S]` or `[\\w\\W]` instead (as in `'/user-[\\s\\S]+/'`.
Examples:
```
// captures '1-a_6' but not '543-azser-sder'
router.get('/[0-9]+-[[\\w]]*', function (req, res, next) { next() })
// captures '1-a_6' and '543-az(ser"-sder' but not '5-a s'
router.get('/[0-9]+-[[\\S]]*', function (req, res, next) { next() })
// captures all (equivalent to '.*')
router.get('[[\\s\\S]]*', function (req, res, next) { next() })
```
### app.path()
Returns the canonical path of the app, a string.
```
var app = express()
var blog = express()
var blogAdmin = express()
app.use('/blog', blog)
blog.use('/admin', blogAdmin)
console.dir(app.path()) // ''
console.dir(blog.path()) // '/blog'
console.dir(blogAdmin.path()) // '/blog/admin'
```
The behavior of this method can become very complicated in complex cases of mounted apps: it is usually better to use [req.baseUrl](#req.baseUrl) to get the canonical path of the app.
### app.post(path, callback [, callback ...])
Routes HTTP POST requests to the specified path with the specified callback functions. For more information, see the [routing guide](https://expressjs.com/guide/routing.html).
#### Arguments
| Argument | Description | Default |
| --- | --- | --- |
| `path` | The path for which the middleware function is invoked; can be any of: * A string representing a path.
* A path pattern.
* A regular expression pattern to match paths.
* An array of combinations of any of the above.
For examples, see [Path examples](#path-examples). | '/' (root path) |
| `callback` | Callback functions; can be: * A middleware function.
* A series of middleware functions (separated by commas).
* An array of middleware functions.
* A combination of all of the above.
You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.
Since [router](#router) and [app](#application) implement the middleware interface, you can use them as you would any other middleware function.
For examples, see [Middleware callback function examples](#middleware-callback-function-examples). | None |
#### Example
```
app.post('/', function (req, res) {
res.send('POST request to homepage')
})
```
### app.put(path, callback [, callback ...])
Routes HTTP PUT requests to the specified path with the specified callback functions.
#### Arguments
| Argument | Description | Default |
| --- | --- | --- |
| `path` | The path for which the middleware function is invoked; can be any of: * A string representing a path.
* A path pattern.
* A regular expression pattern to match paths.
* An array of combinations of any of the above.
For examples, see [Path examples](#path-examples). | '/' (root path) |
| `callback` | Callback functions; can be: * A middleware function.
* A series of middleware functions (separated by commas).
* An array of middleware functions.
* A combination of all of the above.
You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.
Since [router](#router) and [app](#application) implement the middleware interface, you can use them as you would any other middleware function.
For examples, see [Middleware callback function examples](#middleware-callback-function-examples). | None |
#### Example
```
app.put('/', function (req, res) {
res.send('PUT request to homepage')
})
```
### app.render(view, [locals], callback)
Returns the rendered HTML of a view via the `callback` function. It accepts an optional parameter that is an object containing local variables for the view. It is like [res.render()](#res.render), except it cannot send the rendered view to the client on its own.
Think of `app.render()` as a utility function for generating rendered view strings. Internally `res.render()` uses `app.render()` to render views.
The local variable `cache` is reserved for enabling view cache. Set it to `true`, if you want to cache view during development; view caching is enabled in production by default.
```
app.render('email', function (err, html) {
// ...
})
app.render('email', { name: 'Tobi' }, function (err, html) {
// ...
})
```
### app.route(path)
Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use `app.route()` to avoid duplicate route names (and thus typo errors).
```
var app = express()
app.route('/events')
.all(function (req, res, next) {
// runs for all HTTP verbs first
// think of it as route specific middleware!
})
.get(function (req, res, next) {
res.json({})
})
.post(function (req, res, next) {
// maybe add a new event...
})
```
### app.set(name, value)
Assigns setting `name` to `value`. You may store any value that you want, but certain names can be used to configure the behavior of the server. These special names are listed in the [app settings table](#app.settings.table).
Calling `app.set('foo', true)` for a Boolean property is the same as calling `app.enable('foo')`. Similarly, calling `app.set('foo', false)` for a Boolean property is the same as calling `app.disable('foo')`.
Retrieve the value of a setting with [`app.get()`](#app.get).
```
app.set('title', 'My Site')
app.get('title') // "My Site"
```
#### Application Settings
The following table lists application settings.
Note that sub-apps will:
* Not inherit the value of settings that have a default value. You must set the value in the sub-app.
* Inherit the value of settings with no default value; these are explicitly noted in the table below.
Exceptions: Sub-apps will inherit the value of `trust proxy` even though it has a default value (for backward-compatibility); Sub-apps will not inherit the value of `view cache` in production (when `NODE_ENV` is “production”).
| Property | Type | Description | Default |
| --- | --- | --- | --- |
| `case sensitive routing` | Boolean | Enable case sensitivity. When enabled, "/Foo" and "/foo" are different routes. When disabled, "/Foo" and "/foo" are treated the same. **NOTE**: Sub-apps will inherit the value of this setting. | N/A (undefined) |
| `env` | String | Environment mode. Be sure to set to "production" in a production environment; see [Production best practices: performance and reliability](https://expressjs.com/advanced/best-practice-performance.html#env). | `process.env.NODE_ENV` (`NODE_ENV` environment variable) or “development” if `NODE_ENV` is not set. |
| `etag` | Varied | Set the ETag response header. For possible values, see the [`etag` options table](#etag.options.table). [More about the HTTP ETag header](http://en.wikipedia.org/wiki/HTTP_ETag). | `weak` |
| `jsonp callback name` | String | Specifies the default JSONP callback name. | “callback” |
| `json escape` | Boolean | Enable escaping JSON responses from the `res.json`, `res.jsonp`, and `res.send` APIs. This will escape the characters `<`, `>`, and `&` as Unicode escape sequences in JSON. The purpose of this it to assist with [mitigating certain types of persistent XSS attacks](https://blog.mozilla.org/security/2017/07/18/web-service-audits-firefox-accounts/) when clients sniff responses for HTML. **NOTE**: Sub-apps will inherit the value of this setting. | N/A (undefined) |
| `json replacer` | Varied | The ['replacer' argument used by `JSON.stringify`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter). **NOTE**: Sub-apps will inherit the value of this setting. | N/A (undefined) |
| `json spaces` | Varied | The ['space' argument used by `JSON.stringify`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_space_argument). This is typically set to the number of spaces to use to indent prettified JSON. **NOTE**: Sub-apps will inherit the value of this setting. | N/A (undefined) |
| `query parser` | Varied | Disable query parsing by setting the value to `false`, or set the query parser to use either “simple” or “extended” or a custom query string parsing function. The simple query parser is based on Node’s native query parser, [querystring](http://nodejs.org/api/querystring.html). The extended query parser is based on [qs](https://www.npmjs.org/package/qs). A custom query string parsing function will receive the complete query string, and must return an object of query keys and their values. | "extended" |
| `strict routing` | Boolean | Enable strict routing. When enabled, the router treats "/foo" and "/foo/" as different. Otherwise, the router treats "/foo" and "/foo/" as the same. **NOTE**: Sub-apps will inherit the value of this setting. | N/A (undefined) |
| `subdomain offset` | Number | The number of dot-separated parts of the host to remove to access subdomain. | 2 |
| `trust proxy` | Varied | Indicates the app is behind a front-facing proxy, and to use the `X-Forwarded-*` headers to determine the connection and the IP address of the client. NOTE: `X-Forwarded-*` headers are easily spoofed and the detected IP addresses are unreliable. When enabled, Express attempts to determine the IP address of the client connected through the front-facing proxy, or series of proxies. The `req.ips` property, then contains an array of IP addresses the client is connected through. To enable it, use the values described in the [trust proxy options table](#trust.proxy.options.table). The `trust proxy` setting is implemented using the [proxy-addr](https://www.npmjs.org/package/proxy-addr) package. For more information, see its documentation. **NOTE**: Sub-apps *will* inherit the value of this setting, even though it has a default value. | `false` (disabled) |
| `views` | String or Array | A directory or an array of directories for the application's views. If an array, the views are looked up in the order they occur in the array. | `process.cwd() + '/views'` |
| `view cache` | Boolean | Enables view template compilation caching. **NOTE**: Sub-apps will not inherit the value of this setting in production (when `NODE\_ENV` is "production"). | `true` in production, otherwise undefined. |
| `view engine` | String | The default engine extension to use when omitted. **NOTE**: Sub-apps will inherit the value of this setting. | N/A (undefined) |
| `x-powered-by` | Boolean | Enables the "X-Powered-By: Express" HTTP header. | `true` |
##### Options for `trust proxy` setting
Read [Express behind proxies](https://expressjs.com/guide/behind-proxies.html) for more information.
| Type | Value |
| --- | --- |
| Boolean | If `true`, the client’s IP address is understood as the left-most entry in the `X-Forwarded-*` header. If `false`, the app is understood as directly facing the Internet and the client’s IP address is derived from `req.connection.remoteAddress`. This is the default setting. |
| StringString containing comma-separated valuesArray of strings | An IP address, subnet, or an array of IP addresses, and subnets to trust. Pre-configured subnet names are:* loopback - `127.0.0.1/8`, `::1/128`
* linklocal - `169.254.0.0/16`, `fe80::/10`
* uniquelocal - `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `fc00::/7`
Set IP addresses in any of the following ways: Specify a single subnet:
```
app.set('trust proxy', 'loopback')
```
Specify a subnet and an address:
```
app.set('trust proxy', 'loopback, 123.123.123.123')
```
Specify multiple subnets as CSV:
```
app.set('trust proxy', 'loopback, linklocal, uniquelocal')
```
Specify multiple subnets as an array:
```
app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal'])
```
When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client’s IP address. |
| Number | Trust the *n*th hop from the front-facing proxy server as the client. |
| Function | Custom trust implementation. Use this only if you know what you are doing.
```
app.set('trust proxy', function (ip) {
if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs
else return false
})
```
|
##### Options for `etag` setting
**NOTE**: These settings apply only to dynamic files, not static files. The [express.static](#express.static) middleware ignores these settings.
The ETag functionality is implemented using the [etag](https://www.npmjs.org/package/etag) package. For more information, see its documentation.
| Type | Value |
| --- | --- |
| Boolean | `true` enables weak ETag. This is the default setting. `false` disables ETag altogether. |
| String | If "strong", enables strong ETag. If "weak", enables weak ETag. |
| Function | Custom ETag function implementation. Use this only if you know what you are doing.
```
app.set('etag', function (body, encoding) {
return generateHash(body, encoding) // consider the function is defined
})
```
|
### app.use([path,] callback [, callback...])
Mounts the specified [middleware](https://expressjs.com/guide/using-middleware.html) function or functions at the specified path: the middleware function is executed when the base of the requested path matches `path`.
#### Arguments
| Argument | Description | Default |
| --- | --- | --- |
| `path` | The path for which the middleware function is invoked; can be any of: * A string representing a path.
* A path pattern.
* A regular expression pattern to match paths.
* An array of combinations of any of the above.
For examples, see [Path examples](#path-examples). | '/' (root path) |
| `callback` | Callback functions; can be: * A middleware function.
* A series of middleware functions (separated by commas).
* An array of middleware functions.
* A combination of all of the above.
You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.
Since [router](#router) and [app](#application) implement the middleware interface, you can use them as you would any other middleware function.
For examples, see [Middleware callback function examples](#middleware-callback-function-examples). | None |
#### Description
A route will match any path that follows its path immediately with a “`/`”. For example: `app.use('/apple', ...)` will match “/apple”, “/apple/images”, “/apple/images/news”, and so on.
Since `path` defaults to “/”, middleware mounted without a path will be executed for every request to the app.
For example, this middleware function will be executed for *every* request to the app:
```
app.use(function (req, res, next) {
console.log('Time: %d', Date.now())
next()
})
```
**NOTE**
Sub-apps will:
* Not inherit the value of settings that have a default value. You must set the value in the sub-app.
* Inherit the value of settings with no default value.
For details, see [Application settings](index#app.settings.table).
Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.
```
// this middleware will not allow the request to go beyond it
app.use(function (req, res, next) {
res.send('Hello World')
})
// requests will never reach this route
app.get('/', function (req, res) {
res.send('Welcome')
})
```
**Error-handling middleware**
Error-handling middleware always takes *four* arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the `next` object, you must specify it to maintain the signature. Otherwise, the `next` object will be interpreted as regular middleware and will fail to handle errors. For details about error-handling middleware, see: [Error handling](guide/error-handling).
Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`):
```
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
```
#### Path examples
The following table provides some simple examples of valid `path` values for mounting middleware.
| Type | Example |
| --- | --- |
| Path | This will match paths starting with `/abcd`:
```
app.use('/abcd', function (req, res, next) {
next()
})
```
|
| Path Pattern | This will match paths starting with `/abcd` and `/abd`:
```
app.use('/abc?d', function (req, res, next) {
next()
})
```
This will match paths starting with `/abcd`, `/abbcd`, `/abbbbbcd`, and so on:
```
app.use('/ab+cd', function (req, res, next) {
next()
})
```
This will match paths starting with `/abcd`, `/abxcd`, `/abFOOcd`, `/abbArcd`, and so on:
```
app.use('/ab*cd', function (req, res, next) {
next()
})
```
This will match paths starting with `/ad` and `/abcd`:
```
app.use('/a(bc)?d', function (req, res, next) {
next()
})
```
|
| Regular Expression | This will match paths starting with `/abc` and `/xyz`:
```
app.use(/\/abc|\/xyz/, function (req, res, next) {
next()
})
```
|
| Array | This will match paths starting with `/abcd`, `/xyza`, `/lmn`, and `/pqr`:
```
app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], function (req, res, next) {
next()
})
```
|
#### Middleware callback function examples
The following table provides some simple examples of middleware functions that can be used as the `callback` argument to `app.use()`, `app.METHOD()`, and `app.all()`. Even though the examples are for `app.use()`, they are also valid for `app.use()`, `app.METHOD()`, and `app.all()`.
| Usage | Example |
| --- | --- |
| Single Middleware | You can define and mount a middleware function locally.
```
app.use(function (req, res, next) {
next()
})
```
A router is valid middleware.
```
var router = express.Router()
router.get('/', function (req, res, next) {
next()
})
app.use(router)
```
An Express app is valid middleware.
```
var subApp = express()
subApp.get('/', function (req, res, next) {
next()
})
app.use(subApp)
```
|
| Series of Middleware | You can specify more than one middleware function at the same mount path.
```
var r1 = express.Router()
r1.get('/', function (req, res, next) {
next()
})
var r2 = express.Router()
r2.get('/', function (req, res, next) {
next()
})
app.use(r1, r2)
```
|
| Array | Use an array to group middleware logically.
```
var r1 = express.Router()
r1.get('/', function (req, res, next) {
next()
})
var r2 = express.Router()
r2.get('/', function (req, res, next) {
next()
})
app.use([r1, r2])
```
|
| Combination | You can combine all the above ways of mounting middleware.
```
function mw1 (req, res, next) { next() }
function mw2 (req, res, next) { next() }
var r1 = express.Router()
r1.get('/', function (req, res, next) { next() })
var r2 = express.Router()
r2.get('/', function (req, res, next) { next() })
var subApp = express()
subApp.get('/', function (req, res, next) { next() })
app.use(mw1, [mw2, r1, r2], subApp)
```
|
Following are some examples of using the [express.static](https://expressjs.com/guide/using-middleware.html#middleware.built-in) middleware in an Express app.
Serve static content for the app from the “public” directory in the application directory:
```
// GET /style.css etc
app.use(express.static(path.join(__dirname, 'public')))
```
Mount the middleware at “/static” to serve static content only when their request path is prefixed with “/static”:
```
// GET /static/style.css etc.
app.use('/static', express.static(path.join(__dirname, 'public')))
```
Disable logging for static content requests by loading the logger middleware after the static middleware:
```
app.use(express.static(path.join(__dirname, 'public')))
app.use(logger())
```
Serve static files from multiple directories, but give precedence to “./public” over the others:
```
app.use(express.static(path.join(__dirname, 'public')))
app.use(express.static(path.join(__dirname, 'files')))
app.use(express.static(path.join(__dirname, 'uploads')))
```
Request
-------
The `req` object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the object is always referred to as `req` (and the HTTP response is `res`) but its actual name is determined by the parameters to the callback function in which you’re working.
For example:
```
app.get('/user/:id', function (req, res) {
res.send('user ' + req.params.id)
})
```
But you could just as well have:
```
app.get('/user/:id', function (request, response) {
response.send('user ' + request.params.id)
})
```
The `req` object is an enhanced version of Node’s own request object and supports all [built-in fields and methods](https://nodejs.org/api/http.html#http_class_http_incomingmessage).
### Properties
In Express 4, `req.files` is no longer available on the `req` object by default. To access uploaded files on the `req.files` object, use multipart-handling middleware like [busboy](#), [multer](https://www.npmjs.com/package/multer), [formidable](https://www.npmjs.com/package/formidable), [multiparty](https://www.npmjs.com/package/multiparty), [connect-multiparty](https://www.npmjs.com/package/connect-multiparty), or [pez](https://www.npmjs.com/package/pez).
### req.app
This property holds a reference to the instance of the Express application that is using the middleware.
If you follow the pattern in which you create a module that just exports a middleware function and `require()` it in your main file, then the middleware can access the Express instance via `req.app`
For example:
```
// index.js
app.get('/viewdirectory', require('./mymiddleware.js'))
```
```
// mymiddleware.js
module.exports = function (req, res) {
res.send('The views directory is ' + req.app.get('views'))
}
```
### req.baseUrl
The URL path on which a router instance was mounted.
The `req.baseUrl` property is similar to the [mountpath](#app.mountpath) property of the `app` object, except `app.mountpath` returns the matched path pattern(s).
For example:
```
var greet = express.Router()
greet.get('/jp', function (req, res) {
console.log(req.baseUrl) // /greet
res.send('Konichiwa!')
})
app.use('/greet', greet) // load the router on '/greet'
```
Even if you use a path pattern or a set of path patterns to load the router, the `baseUrl` property returns the matched string, not the pattern(s). In the following example, the `greet` router is loaded on two path patterns.
```
app.use(['/gre+t', '/hel{2}o'], greet) // load the router on '/gre+t' and '/hel{2}o'
```
When a request is made to `/greet/jp`, `req.baseUrl` is “/greet”. When a request is made to `/hello/jp`, `req.baseUrl` is “/hello”.
### req.body
Contains key-value pairs of data submitted in the request body. By default, it is `undefined`, and is populated when you use body-parsing middleware such as [`express.json()`](#express.json) or [`express.urlencoded()`](#express.urlencoded).
As `req.body`’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input.
The following example shows how to use body-parsing middleware to populate `req.body`.
```
var express = require('express')
var app = express()
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
app.post('/profile', function (req, res, next) {
console.log(req.body)
res.json(req.body)
})
```
### req.cookies
When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to `{}`.
```
// Cookie: name=tj
console.dir(req.cookies.name)
// => 'tj'
```
If the cookie has been signed, you have to use [req.signedCookies](#req.signedCookies).
For more information, issues, or concerns, see [cookie-parser](https://github.com/expressjs/cookie-parser).
### req.fresh
When the response is still “fresh” in the client’s cache `true` is returned, otherwise `false` is returned to indicate that the client cache is now stale and the full response should be sent.
When a client sends the `Cache-Control: no-cache` request header to indicate an end-to-end reload request, this module will return `false` to make handling these requests transparent.
Further details for how cache validation works can be found in the [HTTP/1.1 Caching Specification](https://tools.ietf.org/html/rfc7234).
```
console.dir(req.fresh)
// => true
```
### req.hostname
Contains the hostname derived from the `Host` HTTP header.
When the [`trust proxy` setting](https://expressjs.com/index.html#trust.proxy.options.table) does not evaluate to `false`, this property will instead get the value from the `X-Forwarded-Host` header field. This header can be set by the client or by the proxy.
If there is more than one `X-Forwarded-Host` header in the request, the value of the first header is used. This includes a single header with comma-separated values, in which the first value is used.
Prior to Express v4.17.0, the `X-Forwarded-Host` could not contain multiple values or be present more than once.
```
// Host: "example.com:3000"
console.dir(req.hostname)
// => 'example.com'
```
### req.ip
Contains the remote IP address of the request.
When the [`trust proxy` setting](https://expressjs.com/index.html#trust.proxy.options.table) does not evaluate to `false`, the value of this property is derived from the left-most entry in the `X-Forwarded-For` header. This header can be set by the client or by the proxy.
```
console.dir(req.ip)
// => '127.0.0.1'
```
### req.ips
When the [`trust proxy` setting](https://expressjs.com/index.html#trust.proxy.options.table) does not evaluate to `false`, this property contains an array of IP addresses specified in the `X-Forwarded-For` request header. Otherwise, it contains an empty array. This header can be set by the client or by the proxy.
For example, if `X-Forwarded-For` is `client, proxy1, proxy2`, `req.ips` would be `["client", "proxy1", "proxy2"]`, where `proxy2` is the furthest downstream.
### req.method
Contains a string corresponding to the HTTP method of the request: `GET`, `POST`, `PUT`, and so on.
### req.originalUrl
`req.url` is not a native Express property, it is inherited from Node’s [http module](https://nodejs.org/api/http.html#http_message_url).
This property is much like `req.url`; however, it retains the original request URL, allowing you to rewrite `req.url` freely for internal routing purposes. For example, the “mounting” feature of [app.use()](#app.use) will rewrite `req.url` to strip the mount point.
```
// GET /search?q=something
console.dir(req.originalUrl)
// => '/search?q=something'
```
`req.originalUrl` is available both in middleware and router objects, and is a combination of `req.baseUrl` and `req.url`. Consider following example:
```
app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new?sort=desc'
console.dir(req.originalUrl) // '/admin/new?sort=desc'
console.dir(req.baseUrl) // '/admin'
console.dir(req.path) // '/new'
next()
})
```
### req.params
This property is an object containing properties mapped to the [named route “parameters”](guide/routing#route-parameters). For example, if you have the route `/user/:name`, then the “name” property is available as `req.params.name`. This object defaults to `{}`.
```
// GET /user/tj
console.dir(req.params.name)
// => 'tj'
```
When you use a regular expression for the route definition, capture groups are provided in the array using `req.params[n]`, where `n` is the nth capture group. This rule is applied to unnamed wild card matches with string routes such as `/file/*`:
```
// GET /file/javascripts/jquery.js
console.dir(req.params[0])
// => 'javascripts/jquery.js'
```
If you need to make changes to a key in `req.params`, use the [app.param](index#app.param) handler. Changes are applicable only to [parameters](guide/routing#route-parameters) already defined in the route path.
Any changes made to the `req.params` object in a middleware or route handler will be reset.
NOTE: Express automatically decodes the values in `req.params` (using `decodeURIComponent`).
### req.path
Contains the path part of the request URL.
```
// example.com/users?sort=desc
console.dir(req.path)
// => '/users'
```
When called from a middleware, the mount point is not included in `req.path`. See [app.use()](https://expressjs.com/index.html#app.use) for more details.
### req.protocol
Contains the request protocol string: either `http` or (for TLS requests) `https`.
When the [`trust proxy` setting](#trust.proxy.options.table) does not evaluate to `false`, this property will use the value of the `X-Forwarded-Proto` header field if present. This header can be set by the client or by the proxy.
```
console.dir(req.protocol)
// => 'http'
```
### req.query
This property is an object containing a property for each query string parameter in the route. When [query parser](#app.settings.table) is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser.
As `req.query`’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.query.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input.
The value of this property can be configured with the [query parser application setting](#app.settings.table) to work how your application needs it. A very popular query string parser is the [`qs` module](https://www.npmjs.org/package/qs), and this is used by default. The `qs` module is very configurable with many settings, and it may be desirable to use different settings than the default to populate `req.query`:
```
var qs = require('qs')
app.setting('query parser', function (str) {
return qs.parse(str, { /* custom options */ })
})
```
Check out the [query parser application setting](#app.settings.table) documentation for other customization options.
### req.res
This property holds a reference to the [response object](#res) that relates to this request object.
### req.route
Contains the currently-matched route, a string. For example:
```
app.get('/user/:id?', function userIdHandler (req, res) {
console.log(req.route)
res.send('GET')
})
```
Example output from the previous snippet:
```
{ path: '/user/:id?',
stack:
[ { handle: [Function: userIdHandler],
name: 'userIdHandler',
params: undefined,
path: undefined,
keys: [],
regexp: /^\/?$/i,
method: 'get' } ],
methods: { get: true } }
```
### req.secure
A Boolean property that is true if a TLS connection is established. Equivalent to:
```
console.dir(req.protocol === 'https')
// => true
```
### req.signedCookies
When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this property contains signed cookies sent by the request, unsigned and ready for use. Signed cookies reside in a different object to show developer intent; otherwise, a malicious attack could be placed on `req.cookie` values (which are easy to spoof). Note that signing a cookie does not make it “hidden” or encrypted; but simply prevents tampering (because the secret used to sign is private).
If no signed cookies are sent, the property defaults to `{}`.
```
// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3
console.dir(req.signedCookies.user)
// => 'tobi'
```
For more information, issues, or concerns, see [cookie-parser](https://github.com/expressjs/cookie-parser).
### req.stale
Indicates whether the request is “stale,” and is the opposite of `req.fresh`. For more information, see [req.fresh](#req.fresh).
```
console.dir(req.stale)
// => true
```
### req.subdomains
An array of subdomains in the domain name of the request.
```
// Host: "tobi.ferrets.example.com"
console.dir(req.subdomains)
// => ['ferrets', 'tobi']
```
The application property `subdomain offset`, which defaults to 2, is used for determining the beginning of the subdomain segments. To change this behavior, change its value using [app.set](index#app.set).
### req.xhr
A Boolean property that is `true` if the request’s `X-Requested-With` header field is “XMLHttpRequest”, indicating that the request was issued by a client library such as jQuery.
```
console.dir(req.xhr)
// => true
```
### Methods
### req.accepts(types)
Checks if the specified content types are acceptable, based on the request’s `Accept` HTTP header field. The method returns the best match, or if none of the specified content types is acceptable, returns `false` (in which case, the application should respond with `406 "Not Acceptable"`).
The `type` value may be a single MIME type string (such as “application/json”), an extension name such as “json”, a comma-delimited list, or an array. For a list or array, the method returns the *best* match (if any).
```
// Accept: text/html
req.accepts('html')
// => "html"
// Accept: text/*, application/json
req.accepts('html')
// => "html"
req.accepts('text/html')
// => "text/html"
req.accepts(['json', 'text'])
// => "json"
req.accepts('application/json')
// => "application/json"
// Accept: text/*, application/json
req.accepts('image/png')
req.accepts('png')
// => false
// Accept: text/*;q=.5, application/json
req.accepts(['html', 'json'])
// => "json"
```
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
### req.acceptsCharsets(charset [, ...])
Returns the first accepted charset of the specified character sets, based on the request’s `Accept-Charset` HTTP header field. If none of the specified charsets is accepted, returns `false`.
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
### req.acceptsEncodings(encoding [, ...])
Returns the first accepted encoding of the specified encodings, based on the request’s `Accept-Encoding` HTTP header field. If none of the specified encodings is accepted, returns `false`.
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
### req.acceptsLanguages(lang [, ...])
Returns the first accepted language of the specified languages, based on the request’s `Accept-Language` HTTP header field. If none of the specified languages is accepted, returns `false`.
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
### req.get(field)
Returns the specified HTTP request header field (case-insensitive match). The `Referrer` and `Referer` fields are interchangeable.
```
req.get('Content-Type')
// => "text/plain"
req.get('content-type')
// => "text/plain"
req.get('Something')
// => undefined
```
Aliased as `req.header(field)`.
### req.is(type)
Returns the matching content type if the incoming request’s “Content-Type” HTTP header field matches the MIME type specified by the `type` parameter. If the request has no body, returns `null`. Returns `false` otherwise.
```
// With Content-Type: text/html; charset=utf-8
req.is('html')
// => 'html'
req.is('text/html')
// => 'text/html'
req.is('text/*')
// => 'text/*'
// When Content-Type is application/json
req.is('json')
// => 'json'
req.is('application/json')
// => 'application/json'
req.is('application/*')
// => 'application/*'
req.is('html')
// => false
```
For more information, or if you have issues or concerns, see [type-is](https://github.com/expressjs/type-is).
### req.param(name [, defaultValue])
Deprecated. Use either `req.params`, `req.body` or `req.query`, as applicable.
Returns the value of param `name` when present.
```
// ?name=tobi
req.param('name')
// => "tobi"
// POST name=tobi
req.param('name')
// => "tobi"
// /user/tobi for /user/:name
req.param('name')
// => "tobi"
```
Lookup is performed in the following order:
* `req.params`
* `req.body`
* `req.query`
Optionally, you can specify `defaultValue` to set a default value if the parameter is not found in any of the request objects.
Direct access to `req.body`, `req.params`, and `req.query` should be favoured for clarity - unless you truly accept input from each object.
Body-parsing middleware must be loaded for `req.param()` to work predictably. Refer [req.body](#req.body) for details.
### req.range(size[, options])
`Range` header parser.
The `size` parameter is the maximum size of the resource.
The `options` parameter is an object that can have the following properties.
| Property | Type | Description |
| --- | --- | --- |
| `combine` | Boolean | Specify if overlapping & adjacent ranges should be combined, defaults to `false`. When `true`, ranges will be combined and returned as if they were specified that way in the header. |
An array of ranges will be returned or negative numbers indicating an error parsing.
* `-2` signals a malformed header string
* `-1` signals an unsatisfiable range
```
// parse header from request
var range = req.range(1000)
// the type of the range
if (range.type === 'bytes') {
// the ranges
range.forEach(function (r) {
// do something with r.start and r.end
})
}
```
Response
--------
The `res` object represents the HTTP response that an Express app sends when it gets an HTTP request.
In this documentation and by convention, the object is always referred to as `res` (and the HTTP request is `req`) but its actual name is determined by the parameters to the callback function in which you’re working.
For example:
```
app.get('/user/:id', function (req, res) {
res.send('user ' + req.params.id)
})
```
But you could just as well have:
```
app.get('/user/:id', function (request, response) {
response.send('user ' + request.params.id)
})
```
The `res` object is an enhanced version of Node’s own response object and supports all [built-in fields and methods](https://nodejs.org/api/http.html#http_class_http_serverresponse).
### Properties
### res.app
This property holds a reference to the instance of the Express application that is using the middleware.
`res.app` is identical to the [req.app](#req.app) property in the request object.
### res.headersSent
Boolean property that indicates if the app sent HTTP headers for the response.
```
app.get('/', function (req, res) {
console.dir(res.headersSent) // false
res.send('OK')
console.dir(res.headersSent) // true
})
```
### res.locals
Use this property to set variables accessible in templates rendered with [res.render](#res.render). The variables set on `res.locals` are available within a single request-response cycle, and will not be shared between requests.
In order to keep local variables for use in template rendering between requests, use [app.locals](#app.locals) instead.
This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on to templates rendered within the application.
```
app.use(function (req, res, next) {
// Make `user` and `authenticated` available in templates
res.locals.user = req.user
res.locals.authenticated = !req.user.anonymous
next()
})
```
### Methods
### res.append(field [, value])
`res.append()` is supported by Express v4.11.0+
Appends the specified `value` to the HTTP response header `field`. If the header is not already set, it creates the header with the specified value. The `value` parameter can be a string or an array.
Note: calling `res.set()` after `res.append()` will reset the previously-set header value.
```
res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>'])
res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly')
res.append('Warning', '199 Miscellaneous warning')
```
### res.attachment([filename])
Sets the HTTP response `Content-Disposition` header field to “attachment”. If a `filename` is given, then it sets the Content-Type based on the extension name via `res.type()`, and sets the `Content-Disposition` “filename=” parameter.
```
res.attachment()
// Content-Disposition: attachment
res.attachment('path/to/logo.png')
// Content-Disposition: attachment; filename="logo.png"
// Content-Type: image/png
```
### res.cookie(name, value [, options])
Sets cookie `name` to `value`. The `value` parameter may be a string or object converted to JSON.
The `options` parameter is an object that can have the following properties.
| Property | Type | Description |
| --- | --- | --- |
| `domain` | String | Domain name for the cookie. Defaults to the domain name of the app. |
| `encode` | Function | A synchronous function used for cookie value encoding. Defaults to `encodeURIComponent`. |
| `expires` | Date | Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie. |
| `httpOnly` | Boolean | Flags the cookie to be accessible only by the web server. |
| `maxAge` | Number | Convenient option for setting the expiry time relative to the current time in milliseconds. |
| `path` | String | Path for the cookie. Defaults to “/”. |
| `priority` | String | Value of the “Priority” **Set-Cookie** attribute. |
| `secure` | Boolean | Marks the cookie to be used with HTTPS only. |
| `signed` | Boolean | Indicates if the cookie should be signed. |
| `sameSite` | Boolean or String | Value of the “SameSite” **Set-Cookie** attribute. More information at <https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1>. |
All `res.cookie()` does is set the HTTP `Set-Cookie` header with the options provided. Any option not specified defaults to the value stated in [RFC 6265](http://tools.ietf.org/html/rfc6265).
For example:
```
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true })
res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })
```
You can set multiple cookies in a single response by calling `res.cookie` multiple times, for example:
```
res
.status(201)
.cookie('access_token', 'Bearer ' + token, {
expires: new Date(Date.now() + 8 * 3600000) // cookie will be removed after 8 hours
})
.cookie('test', 'test')
.redirect(301, '/admin')
```
The `encode` option allows you to choose the function used for cookie value encoding. Does not support asynchronous functions.
Example use case: You need to set a domain-wide cookie for another site in your organization. This other site (not under your administrative control) does not use URI-encoded cookie values.
```
// Default encoding
res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com' })
// Result: 'some_cross_domain_cookie=http%3A%2F%2Fmysubdomain.example.com; Domain=example.com; Path=/'
// Custom encoding
res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com', encode: String })
// Result: 'some_cross_domain_cookie=http://mysubdomain.example.com; Domain=example.com; Path=/;'
```
The `maxAge` option is a convenience option for setting “expires” relative to the current time in milliseconds. The following is equivalent to the second example above.
```
res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
```
You can pass an object as the `value` parameter; it is then serialized as JSON and parsed by `bodyParser()` middleware.
```
res.cookie('cart', { items: [1, 2, 3] })
res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 })
```
When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this method also supports signed cookies. Simply include the `signed` option set to `true`. Then `res.cookie()` will use the secret passed to `cookieParser(secret)` to sign the value.
```
res.cookie('name', 'tobi', { signed: true })
```
Later you may access this value through the [req.signedCookie](#req.signedCookies) object.
### res.clearCookie(name [, options])
Clears the cookie specified by `name`. For details about the `options` object, see [res.cookie()](#res.cookie).
Web browsers and other compliant clients will only clear the cookie if the given `options` is identical to those given to [res.cookie()](#res.cookie), excluding `expires` and `maxAge`.
```
res.cookie('name', 'tobi', { path: '/admin' })
res.clearCookie('name', { path: '/admin' })
```
### res.download(path [, filename] [, options] [, fn])
Transfers the file at `path` as an “attachment”. Typically, browsers will prompt the user for download. By default, the `Content-Disposition` header “filename=” parameter is derrived from the `path` argument, but can be overridden with the `filename` parameter. If `path` is relative, then it will be based on the current working directory of the process or the `root` option, if provided.
This API provides access to data on the running file system. Ensure that either (a) the way in which the `path` argument was constructed is secure if it contains user input or (b) set the `root` option to the absolute path of a directory to contain access within.
When the `root` option is provided, Express will validate that the relative path provided as `path` will resolve within the given `root` option.
The following table provides details on the `options` parameter.
The optional `options` argument is supported by Express v4.16.0 onwards.
| Property | Description | Default | Availability |
| --- | --- | --- | --- |
| `maxAge` | Sets the max-age property of the `Cache-Control` header in milliseconds or a string in [ms format](https://www.npmjs.org/package/ms) | 0 | 4.16+ |
| `root` | Root directory for relative filenames. | | 4.18+ |
| `lastModified` | Sets the `Last-Modified` header to the last modified date of the file on the OS. Set `false` to disable it. | Enabled | 4.16+ |
| `headers` | Object containing HTTP headers to serve with the file. The header `Content-Disposition` will be overriden by the `filename` argument. | | 4.16+ |
| `dotfiles` | Option for serving dotfiles. Possible values are “allow”, “deny”, “ignore”. | “ignore” | 4.16+ |
| `acceptRanges` | Enable or disable accepting ranged requests. | `true` | 4.16+ |
| `cacheControl` | Enable or disable setting `Cache-Control` response header. | `true` | 4.16+ |
| `immutable` | Enable or disable the `immutable` directive in the `Cache-Control` response header. If enabled, the `maxAge` option should also be specified to enable caching. The `immutable` directive will prevent supported clients from making conditional requests during the life of the `maxAge` option to check if the file has changed. | `false` | 4.16+ |
The method invokes the callback function `fn(err)` when the transfer is complete or when an error occurs. If the callback function is specified and an error occurs, the callback function must explicitly handle the response process either by ending the request-response cycle, or by passing control to the next route.
```
res.download('/report-12345.pdf')
res.download('/report-12345.pdf', 'report.pdf')
res.download('/report-12345.pdf', 'report.pdf', function (err) {
if (err) {
// Handle error, but keep in mind the response may be partially-sent
// so check res.headersSent
} else {
// decrement a download credit, etc.
}
})
```
### res.end([data] [, encoding])
Ends the response process. This method actually comes from Node core, specifically the [response.end() method of http.ServerResponse](https://nodejs.org/api/http.html#http_response_end_data_encoding_callback).
Use to quickly end the response without any data. If you need to respond with data, instead use methods such as [res.send()](#res.send) and [res.json()](#res.json).
```
res.end()
res.status(404).end()
```
### res.format(object)
Performs content-negotiation on the `Accept` HTTP header on the request object, when present. It uses [req.accepts()](#req.accepts) to select a handler for the request, based on the acceptable types ordered by their quality values. If the header is not specified, the first callback is invoked. When no match is found, the server responds with 406 “Not Acceptable”, or invokes the `default` callback.
The `Content-Type` response header is set when a callback is selected. However, you may alter this within the callback using methods such as `res.set()` or `res.type()`.
The following example would respond with `{ "message": "hey" }` when the `Accept` header field is set to “application/json” or “\*/json” (however if it is “\*/\*”, then the response will be “hey”).
```
res.format({
'text/plain': function () {
res.send('hey')
},
'text/html': function () {
res.send('<p>hey</p>')
},
'application/json': function () {
res.send({ message: 'hey' })
},
default: function () {
// log the request and respond with 406
res.status(406).send('Not Acceptable')
}
})
```
In addition to canonicalized MIME types, you may also use extension names mapped to these types for a slightly less verbose implementation:
```
res.format({
text: function () {
res.send('hey')
},
html: function () {
res.send('<p>hey</p>')
},
json: function () {
res.send({ message: 'hey' })
}
})
```
### res.get(field)
Returns the HTTP response header specified by `field`. The match is case-insensitive.
```
res.get('Content-Type')
// => "text/plain"
```
### res.json([body])
Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).
The parameter can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON.
```
res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })
```
### res.jsonp([body])
Sends a JSON response with JSONP support. This method is identical to `res.json()`, except that it opts-in to JSONP callback support.
```
res.jsonp(null)
// => callback(null)
res.jsonp({ user: 'tobi' })
// => callback({ "user": "tobi" })
res.status(500).jsonp({ error: 'message' })
// => callback({ "error": "message" })
```
By default, the JSONP callback name is simply `callback`. Override this with the [jsonp callback name](#app.settings.table) setting.
The following are some examples of JSONP responses using the same code:
```
// ?callback=foo
res.jsonp({ user: 'tobi' })
// => foo({ "user": "tobi" })
app.set('jsonp callback name', 'cb')
// ?cb=foo
res.status(500).jsonp({ error: 'message' })
// => foo({ "error": "message" })
```
### res.links(links)
Joins the `links` provided as properties of the parameter to populate the response’s `Link` HTTP header field.
For example, the following call:
```
res.links({
next: 'http://api.example.com/users?page=2',
last: 'http://api.example.com/users?page=5'
})
```
Yields the following results:
```
Link: <http://api.example.com/users?page=2>; rel="next",
<http://api.example.com/users?page=5>; rel="last"
```
### res.location(path)
Sets the response `Location` HTTP header to the specified `path` parameter.
```
res.location('/foo/bar')
res.location('http://example.com')
res.location('back')
```
A `path` value of “back” has a special meaning, it refers to the URL specified in the `Referer` header of the request. If the `Referer` header was not specified, it refers to “/”.
After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the `Location` header, without any validation.
Browsers take the responsibility of deriving the intended URL from the current URL or the referring URL, and the URL specified in the `Location` header; and redirect the user accordingly.
### res.redirect([status,] path)
Redirects to the URL derived from the specified `path`, with specified `status`, a positive integer that corresponds to an [HTTP status code](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) . If not specified, `status` defaults to “302 “Found”.
```
res.redirect('/foo/bar')
res.redirect('http://example.com')
res.redirect(301, 'http://example.com')
res.redirect('../login')
```
Redirects can be a fully-qualified URL for redirecting to a different site:
```
res.redirect('http://google.com')
```
Redirects can be relative to the root of the host name. For example, if the application is on `http://example.com/admin/post/new`, the following would redirect to the URL `http://example.com/admin`:
```
res.redirect('/admin')
```
Redirects can be relative to the current URL. For example, from `http://example.com/blog/admin/` (notice the trailing slash), the following would redirect to the URL `http://example.com/blog/admin/post/new`.
```
res.redirect('post/new')
```
Redirecting to `post/new` from `http://example.com/blog/admin` (no trailing slash), will redirect to `http://example.com/blog/post/new`.
If you found the above behavior confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense.
Path-relative redirects are also possible. If you were on `http://example.com/admin/post/new`, the following would redirect to `http://example.com/admin/post`:
```
res.redirect('..')
```
A `back` redirection redirects the request back to the [referer](http://en.wikipedia.org/wiki/HTTP_referer), defaulting to `/` when the referer is missing.
```
res.redirect('back')
```
### res.render(view [, locals] [, callback])
Renders a `view` and sends the rendered HTML string to the client. Optional parameters:
* `locals`, an object whose properties define local variables for the view.
* `callback`, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes `next(err)` internally.
The `view` argument is a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the `views` setting. If the path does not contain a file extension, then the `view engine` setting determines the file extension. If the path does contain a file extension, then Express will load the module for the specified template engine (via `require()`) and render it using the loaded module’s `__express` function.
For more information, see [Using template engines with Express](https://expressjs.com/guide/using-template-engines.html).
**NOTE:** The `view` argument performs file system operations like reading a file from disk and evaluating Node.js modules, and as so for security reasons should not contain input from the end-user.
The local variable `cache` enables view caching. Set it to `true`, to cache the view during development; view caching is enabled in production by default.
```
// send the rendered view to the client
res.render('index')
// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', function (err, html) {
res.send(html)
})
// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function (err, html) {
// ...
})
```
### res.req
This property holds a reference to the [request object](#req) that relates to this response object. ### res.send([body])
Sends the HTTP response.
The `body` parameter can be a `Buffer` object, a `String`, an object, `Boolean`, or an `Array`. For example:
```
res.send(Buffer.from('whoop'))
res.send({ some: 'json' })
res.send('<p>some html</p>')
res.status(404).send('Sorry, we cannot find that!')
res.status(500).send({ error: 'something blew up' })
```
This method performs many useful tasks for simple non-streaming responses: For example, it automatically assigns the `Content-Length` HTTP response header field (unless previously defined) and provides automatic HEAD and HTTP cache freshness support.
When the parameter is a `Buffer` object, the method sets the `Content-Type` response header field to “application/octet-stream”, unless previously defined as shown below:
```
res.set('Content-Type', 'text/html')
res.send(Buffer.from('<p>some html</p>'))
```
When the parameter is a `String`, the method sets the `Content-Type` to “text/html”:
```
res.send('<p>some html</p>')
```
When the parameter is an `Array` or `Object`, Express responds with the JSON representation:
```
res.send({ user: 'tobi' })
res.send([1, 2, 3])
```
### res.sendFile(path [, options] [, fn])
`res.sendFile()` is supported by Express v4.8.0 onwards.
Transfers the file at the given `path`. Sets the `Content-Type` response HTTP header field based on the filename’s extension. Unless the `root` option is set in the options object, `path` must be an absolute path to the file.
This API provides access to data on the running file system. Ensure that either (a) the way in which the `path` argument was constructed into an absolute path is secure if it contains user input or (b) set the `root` option to the absolute path of a directory to contain access within.
When the `root` option is provided, the `path` argument is allowed to be a relative path, including containing `..`. Express will validate that the relative path provided as `path` will resolve within the given `root` option.
The following table provides details on the `options` parameter.
| Property | Description | Default | Availability |
| --- | --- | --- | --- |
| `maxAge` | Sets the max-age property of the `Cache-Control` header in milliseconds or a string in [ms format](https://www.npmjs.org/package/ms) | 0 | |
| `root` | Root directory for relative filenames. | | |
| `lastModified` | Sets the `Last-Modified` header to the last modified date of the file on the OS. Set `false` to disable it. | Enabled | 4.9.0+ |
| `headers` | Object containing HTTP headers to serve with the file. | | |
| `dotfiles` | Option for serving dotfiles. Possible values are “allow”, “deny”, “ignore”. | “ignore” | |
| `acceptRanges` | Enable or disable accepting ranged requests. | `true` | 4.14+ |
| `cacheControl` | Enable or disable setting `Cache-Control` response header. | `true` | 4.14+ |
| `immutable` | Enable or disable the `immutable` directive in the `Cache-Control` response header. If enabled, the `maxAge` option should also be specified to enable caching. The `immutable` directive will prevent supported clients from making conditional requests during the life of the `maxAge` option to check if the file has changed. | `false` | 4.16+ |
The method invokes the callback function `fn(err)` when the transfer is complete or when an error occurs. If the callback function is specified and an error occurs, the callback function must explicitly handle the response process either by ending the request-response cycle, or by passing control to the next route.
Here is an example of using `res.sendFile` with all its arguments.
```
app.get('/file/:name', function (req, res, next) {
var options = {
root: path.join(__dirname, 'public'),
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
}
var fileName = req.params.name
res.sendFile(fileName, options, function (err) {
if (err) {
next(err)
} else {
console.log('Sent:', fileName)
}
})
})
```
The following example illustrates using `res.sendFile` to provide fine-grained support for serving files:
```
app.get('/user/:uid/photos/:file', function (req, res) {
var uid = req.params.uid
var file = req.params.file
req.user.mayViewFilesFrom(uid, function (yes) {
if (yes) {
res.sendFile('/uploads/' + uid + '/' + file)
} else {
res.status(403).send("Sorry! You can't see that.")
}
})
})
```
For more information, or if you have issues or concerns, see [send](https://github.com/pillarjs/send).
### res.sendStatus(statusCode)
Sets the response HTTP status code to `statusCode` and sends the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number.
```
res.sendStatus(404)
```
Some versions of Node.js will throw when `res.statusCode` is set to an invalid HTTP status code (outside of the range `100` to `599`). Consult the HTTP server documentation for the Node.js version being used.
[More about HTTP Status Codes](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes)
### res.set(field [, value])
Sets the response’s HTTP header `field` to `value`. To set multiple fields at once, pass an object as the parameter.
```
res.set('Content-Type', 'text/plain')
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
ETag: '12345'
})
```
Aliased as `res.header(field [, value])`.
### res.status(code)
Sets the HTTP status for the response. It is a chainable alias of Node’s [response.statusCode](http://nodejs.org/api/http.html#http_response_statuscode).
```
res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')
```
### res.type(type)
Sets the `Content-Type` HTTP header to the MIME type as determined by the specified `type`. If `type` contains the “/” character, then it sets the `Content-Type` to the exact value of `type`, otherwise it is assumed to be a file extension and the MIME type is looked up in a mapping using the `express.static.mime.lookup()` method.
```
res.type('.html')
// => 'text/html'
res.type('html')
// => 'text/html'
res.type('json')
// => 'application/json'
res.type('application/json')
// => 'application/json'
res.type('png')
// => 'image/png'
```
### res.vary(field)
Adds the field to the `Vary` response header, if it is not there already.
```
res.vary('User-Agent').render('docs')
```
Router
------
A `router` object is an isolated instance of middleware and routes. You can think of it as a “mini-application,” capable only of performing middleware and routing functions. Every Express application has a built-in app router.
A router behaves like middleware itself, so you can use it as an argument to [app.use()](#app.use) or as the argument to another router’s [use()](#router.use) method.
The top-level `express` object has a [Router()](#express.router) method that creates a new `router` object.
Once you’ve created a router object, you can add middleware and HTTP method routes (such as `get`, `put`, `post`, and so on) to it just like an application. For example:
```
// invoked for any requests passed to this router
router.use(function (req, res, next) {
// .. some logic here .. like any other middleware
next()
})
// will handle any request that ends in /events
// depends on where the router is "use()'d"
router.get('/events', function (req, res, next) {
// ..
})
```
You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps.
```
// only requests to /calendar/* will be sent to our "router"
app.use('/calendar', router)
```
### Methods
### router.all(path, [callback, ...] callback)
This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches. For example, if you placed the following route at the top of all other route definitions, it would require that all routes from that point on would require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end points; `loadUser` can perform a task, then call `next()` to continue matching subsequent routes.
```
router.all('*', requireAuthentication, loadUser)
```
Or the equivalent:
```
router.all('*', requireAuthentication)
router.all('*', loadUser)
```
Another example of this is white-listed “global” functionality. Here the example is much like before, but it only restricts paths prefixed with “/api”:
```
router.all('/api/*', requireAuthentication)
```
### router.METHOD(path, [callback, ...] callback)
The `router.METHOD()` methods provide the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are `router.get()`, `router.post()`, `router.put()`, and so on.
The `router.get()` function is automatically called for the HTTP `HEAD` method in addition to the `GET` method if `router.head()` was not called for the path before `router.get()`.
You can provide multiple callbacks, and all are treated equally, and behave just like middleware, except that these callbacks may invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to perform pre-conditions on a route then pass control to subsequent routes when there is no reason to proceed with the route matched.
The following snippet illustrates the most simple route definition possible. Express translates the path strings to regular expressions, used internally to match incoming requests. Query strings are *not* considered when performing these matches, for example “GET /” would match the following route, as would “GET /?name=tobi”.
```
router.get('/', function (req, res) {
res.send('hello world')
})
```
You can also use regular expressions—useful if you have very specific constraints, for example the following would match “GET /commits/71dbb9c” as well as “GET /commits/71dbb9c..4c084f9”.
```
router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function (req, res) {
var from = req.params[0]
var to = req.params[1] || 'HEAD'
res.send('commit range ' + from + '..' + to)
})
```
### router.param(name, callback)
Adds callback triggers to route parameters, where `name` is the name of the parameter and `callback` is the callback function. Although `name` is technically optional, using this method without it is deprecated starting with Express v4.11.0 (see below).
The parameters of the callback function are:
* `req`, the request object.
* `res`, the response object.
* `next`, indicating the next middleware function.
* The value of the `name` parameter.
* The name of the parameter.
Unlike `app.param()`, `router.param()` does not accept an array of route parameters.
For example, when `:user` is present in a route path, you may map user loading logic to automatically provide `req.user` to the route, or perform validations on the parameter input.
```
router.param('user', function (req, res, next, id) {
// try to get the user details from the User model and attach it to the request object
User.find(id, function (err, user) {
if (err) {
next(err)
} else if (user) {
req.user = user
next()
} else {
next(new Error('failed to load user'))
}
})
})
```
Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers. Hence, param callbacks defined on `router` will be triggered only by route parameters defined on `router` routes.
A param callback will be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.
```
router.param('id', function (req, res, next, id) {
console.log('CALLED ONLY ONCE')
next()
})
router.get('/user/:id', function (req, res, next) {
console.log('although this matches')
next()
})
router.get('/user/:id', function (req, res) {
console.log('and this matches too')
res.end()
})
```
On `GET /user/42`, the following is printed:
```
CALLED ONLY ONCE
although this matches
and this matches too
```
The following section describes `router.param(callback)`, which is deprecated as of v4.11.0.
The behavior of the `router.param(name, callback)` method can be altered entirely by passing only a function to `router.param()`. This function is a custom implementation of how `router.param(name, callback)` should behave - it accepts two parameters and must return a middleware.
The first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation.
The middleware returned by the function decides the behavior of what happens when a URL parameter is captured.
In this example, the `router.param(name, callback)` signature is modified to `router.param(name, accessId)`. Instead of accepting a name and a callback, `router.param()` will now accept a name and a number.
```
var express = require('express')
var app = express()
var router = express.Router()
// customizing the behavior of router.param()
router.param(function (param, option) {
return function (req, res, next, val) {
if (val === option) {
next()
} else {
res.sendStatus(403)
}
}
})
// using the customized router.param()
router.param('id', '1337')
// route to trigger the capture
router.get('/user/:id', function (req, res) {
res.send('OK')
})
app.use(router)
app.listen(3000, function () {
console.log('Ready')
})
```
In this example, the `router.param(name, callback)` signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id.
```
router.param(function (param, validator) {
return function (req, res, next, val) {
if (validator(val)) {
next()
} else {
res.sendStatus(403)
}
}
})
router.param('id', function (candidate) {
return !isNaN(parseFloat(candidate)) && isFinite(candidate)
})
```
### router.route(path)
Returns an instance of a single route which you can then use to handle HTTP verbs with optional middleware. Use `router.route()` to avoid duplicate route naming and thus typing errors.
Building on the `router.param()` example above, the following code shows how to use `router.route()` to specify various HTTP method handlers.
```
var router = express.Router()
router.param('user_id', function (req, res, next, id) {
// sample user, would actually fetch from DB, etc...
req.user = {
id: id,
name: 'TJ'
}
next()
})
router.route('/users/:user_id')
.all(function (req, res, next) {
// runs for all HTTP verbs first
// think of it as route specific middleware!
next()
})
.get(function (req, res, next) {
res.json(req.user)
})
.put(function (req, res, next) {
// just an example of maybe updating the user
req.user.name = req.params.name
// save user ... etc
res.json(req.user)
})
.post(function (req, res, next) {
next(new Error('not implemented'))
})
.delete(function (req, res, next) {
next(new Error('not implemented'))
})
```
This approach re-uses the single `/users/:user_id` path and adds handlers for various HTTP methods.
NOTE: When you use `router.route()`, middleware ordering is based on when the *route* is created, not when method handlers are added to the route. For this purpose, you can consider method handlers to belong to the route to which they were added.
### router.use([path], [function, ...] function)
Uses the specified middleware function or functions, with optional mount path `path`, that defaults to “/”.
This method is similar to [app.use()](#app.use). A simple example and use case is described below. See [app.use()](#app.use) for more information.
Middleware is like a plumbing pipe: requests start at the first middleware function defined and work their way “down” the middleware stack processing for each path they match.
```
var express = require('express')
var app = express()
var router = express.Router()
// simple logger for this router's requests
// all requests to this router will first hit this middleware
router.use(function (req, res, next) {
console.log('%s %s %s', req.method, req.url, req.path)
next()
})
// this will only be invoked if the path starts with /bar from the mount point
router.use('/bar', function (req, res, next) {
// ... maybe some additional /bar logging ...
next()
})
// always invoked
router.use(function (req, res, next) {
res.send('Hello World')
})
app.use('/foo', router)
app.listen(3000)
```
The “mount” path is stripped and is *not* visible to the middleware function. The main effect of this feature is that a mounted middleware function may operate without code changes regardless of its “prefix” pathname.
The order in which you define middleware with `router.use()` is very important. They are invoked sequentially, thus the order defines middleware precedence. For example, usually a logger is the very first middleware you would use, so that every request gets logged.
```
var logger = require('morgan')
var path = require('path')
router.use(logger())
router.use(express.static(path.join(__dirname, 'public')))
router.use(function (req, res) {
res.send('Hello')
})
```
Now suppose you wanted to ignore logging requests for static files, but to continue logging routes and middleware defined after `logger()`. You would simply move the call to `express.static()` to the top, before adding the logger middleware:
```
router.use(express.static(path.join(__dirname, 'public')))
router.use(logger())
router.use(function (req, res) {
res.send('Hello')
})
```
Another example is serving files from multiple directories, giving precedence to “./public” over the others:
```
router.use(express.static(path.join(__dirname, 'public')))
router.use(express.static(path.join(__dirname, 'files')))
router.use(express.static(path.join(__dirname, 'uploads')))
```
The `router.use()` method also supports named parameters so that your mount points for other routers can benefit from preloading using named parameters.
**NOTE**: Although these middleware functions are added via a particular router, *when* they run is defined by the path they are attached to (not the router). Therefore, middleware added via one router may run for other routers if its routes match. For example, this code shows two different routers mounted on the same path:
```
var authRouter = express.Router()
var openRouter = express.Router()
authRouter.use(require('./authenticate').basic(usersdb))
authRouter.get('/:user_id/edit', function (req, res, next) {
// ... Edit user UI ...
})
openRouter.get('/', function (req, res, next) {
// ... List users ...
})
openRouter.get('/:user_id', function (req, res, next) {
// ... View user ...
})
app.use('/users', authRouter)
app.use('/users', openRouter)
```
Even though the authentication middleware was added via the `authRouter` it will run on the routes defined by the `openRouter` as well since both routers were mounted on `/users`. To avoid this behavior, use different paths for each router.
| programming_docs |
express Database integration Database integration
====================
Adding the capability to connect databases to Express apps is just a matter of loading an appropriate Node.js driver for the database in your app. This document briefly explains how to add and use some of the most popular Node.js modules for database systems in your Express app:
* [Cassandra](#cassandra)
* [Couchbase](#couchbase)
* [CouchDB](#couchdb)
* [LevelDB](#leveldb)
* [MySQL](#mysql)
* [MongoDB](#mongodb)
* [Neo4j](#neo4j)
* [Oracle](#oracle)
* [PostgreSQL](#postgresql)
* [Redis](#redis)
* [SQL Server](#sql-server)
* [SQLite](#sqlite)
* [Elasticsearch](#elasticsearch)
These database drivers are among many that are available. For other options, search on the [npm](https://www.npmjs.com/) site.
Cassandra
---------
**Module**: [cassandra-driver](https://github.com/datastax/nodejs-driver)
### Installation
```
$ npm install cassandra-driver
```
### Example
```
const cassandra = require('cassandra-driver')
const client = new cassandra.Client({ contactPoints: ['localhost'] })
client.execute('select key from system.local', (err, result) => {
if (err) throw err
console.log(result.rows[0])
})
```
Couchbase
---------
**Module**: [couchnode](https://github.com/couchbase/couchnode)
### Installation
```
$ npm install couchbase
```
### Example
```
const couchbase = require('couchbase')
const bucket = (new couchbase.Cluster('http://localhost:8091')).openBucket('bucketName')
// add a document to a bucket
bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
// get all documents with shoe size 13
const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1'
const query = N1qlQuery.fromString(n1ql)
bucket.query(query, [13], (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
```
CouchDB
-------
**Module**: [nano](https://github.com/dscape/nano)
### Installation
```
$ npm install nano
```
### Example
```
const nano = require('nano')('http://localhost:5984')
nano.db.create('books')
const books = nano.db.use('books')
// Insert a book document in the books database
books.insert({ name: 'The Art of war' }, null, (err, body) => {
if (err) {
console.log(err)
} else {
console.log(body)
}
})
// Get a list of all books
books.list((err, body) => {
if (err) {
console.log(err)
} else {
console.log(body.rows)
}
})
```
LevelDB
-------
**Module**: [levelup](https://github.com/rvagg/node-levelup)
### Installation
```
$ npm install level levelup leveldown
```
### Example
```
const levelup = require('levelup')
const db = levelup('./mydb')
db.put('name', 'LevelUP', (err) => {
if (err) return console.log('Ooops!', err)
db.get('name', (err, value) => {
if (err) return console.log('Ooops!', err)
console.log(`name=${value}`)
})
})
```
MySQL
-----
**Module**: [mysql](https://github.com/felixge/node-mysql/)
### Installation
```
$ npm install mysql
```
### Example
```
const mysql = require('mysql')
const connection = mysql.createConnection({
host: 'localhost',
user: 'dbuser',
password: 's3kreee7',
database: 'my_db'
})
connection.connect()
connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
if (err) throw err
console.log('The solution is: ', rows[0].solution)
})
connection.end()
```
MongoDB
-------
**Module**: [mongodb](https://github.com/mongodb/node-mongodb-native)
### Installation
```
$ npm install mongodb
```
### Example (v2.\*)
```
const MongoClient = require('mongodb').MongoClient
MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
if (err) throw err
db.collection('mammals').find().toArray((err, result) => {
if (err) throw err
console.log(result)
})
})
```
### Example (v3.\*)
```
const MongoClient = require('mongodb').MongoClient
MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
if (err) throw err
const db = client.db('animals')
db.collection('mammals').find().toArray((err, result) => {
if (err) throw err
console.log(result)
})
})
```
If you want an object model driver for MongoDB, look at [Mongoose](https://github.com/LearnBoost/mongoose).
Neo4j
-----
**Module**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
### Installation
```
$ npm install neo4j-driver
```
### Example
```
const neo4j = require('neo4j-driver')
const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'))
const session = driver.session()
session.readTransaction((tx) => {
return tx.run('MATCH (n) RETURN count(n) AS count')
.then((res) => {
console.log(res.records[0].get('count'))
})
.catch((error) => {
console.log(error)
})
})
```
Oracle
------
**Module**: [oracledb](https://github.com/oracle/node-oracledb)
### Installation
NOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation).
```
$ npm install oracledb
```
### Example
```
const oracledb = require('oracledb')
const config = {
user: '<your db user>',
password: '<your db password>',
connectString: 'localhost:1521/orcl'
}
async function getEmployee (empId) {
let conn
try {
conn = await oracledb.getConnection(config)
const result = await conn.execute(
'select * from employees where employee_id = :id',
[empId]
)
console.log(result.rows[0])
} catch (err) {
console.log('Ouch!', err)
} finally {
if (conn) { // conn assignment worked, need to close
await conn.close()
}
}
}
getEmployee(101)
```
PostgreSQL
----------
**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise)
### Installation
```
$ npm install pg-promise
```
### Example
```
const pgp = require('pg-promise')(/* options */)
const db = pgp('postgres://username:password@host:port/database')
db.one('SELECT $1 AS value', 123)
.then((data) => {
console.log('DATA:', data.value)
})
.catch((error) => {
console.log('ERROR:', error)
})
```
Redis
-----
**Module**: [redis](https://github.com/mranney/node_redis)
### Installation
```
$ npm install redis
```
### Example
```
const redis = require('redis')
const client = redis.createClient()
client.on('error', (err) => {
console.log(`Error ${err}`)
})
client.set('string key', 'string val', redis.print)
client.hset('hash key', 'hashtest 1', 'some value', redis.print)
client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print)
client.hkeys('hash key', (err, replies) => {
console.log(`${replies.length} replies:`)
replies.forEach((reply, i) => {
console.log(` ${i}: ${reply}`)
})
client.quit()
})
```
SQL Server
----------
**Module**: [tedious](https://github.com/tediousjs/tedious)
### Installation
```
$ npm install tedious
```
### Example
```
const Connection = require('tedious').Connection
const Request = require('tedious').Request
const config = {
server: 'localhost',
authentication: {
type: 'default',
options: {
userName: 'your_username', // update me
password: 'your_password' // update me
}
}
}
const connection = new Connection(config)
connection.on('connect', (err) => {
if (err) {
console.log(err)
} else {
executeStatement()
}
})
function executeStatement () {
request = new Request("select 123, 'hello world'", (err, rowCount) => {
if (err) {
console.log(err)
} else {
console.log(`${rowCount} rows`)
}
connection.close()
})
request.on('row', (columns) => {
columns.forEach((column) => {
if (column.value === null) {
console.log('NULL')
} else {
console.log(column.value)
}
})
})
connection.execSql(request)
}
```
SQLite
------
**Module**: [sqlite3](https://github.com/mapbox/node-sqlite3)
### Installation
```
$ npm install sqlite3
```
### Example
```
const sqlite3 = require('sqlite3').verbose()
const db = new sqlite3.Database(':memory:')
db.serialize(() => {
db.run('CREATE TABLE lorem (info TEXT)')
const stmt = db.prepare('INSERT INTO lorem VALUES (?)')
for (let i = 0; i < 10; i++) {
stmt.run(`Ipsum ${i}`)
}
stmt.finalize()
db.each('SELECT rowid AS id, info FROM lorem', (err, row) => {
console.log(`${row.id}: ${row.info}`)
})
})
db.close()
```
Elasticsearch
-------------
**Module**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
### Installation
```
$ npm install elasticsearch
```
### Example
```
const elasticsearch = require('elasticsearch')
const client = elasticsearch.Client({
host: 'localhost:9200'
})
client.search({
index: 'books',
type: 'book',
body: {
query: {
multi_match: {
query: 'express js',
fields: ['title', 'description']
}
}
}
}).then((response) => {
const hits = response.hits.hits
}, (error) => {
console.trace(error.message)
})
```
express Writing middleware for use in Express apps Writing middleware for use in Express apps
==========================================
Overview
--------
*Middleware* functions are functions that have access to the [request object](../index#req) (`req`), the [response object](../index#res) (`res`), and the `next` function in the application’s request-response cycle. The `next` function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
Middleware functions can perform the following tasks:
* Execute any code.
* Make changes to the request and the response objects.
* End the request-response cycle.
* Call the next middleware in the stack.
If the current middleware function does not end the request-response cycle, it must call `next()` to pass control to the next middleware function. Otherwise, the request will be left hanging.
The following figure shows the elements of a middleware function call:
| | |
| --- | --- |
| | HTTP method for which the middleware function applies. Path (route) for which the middleware function applies. The middleware function. Callback argument to the middleware function, called "next" by convention. HTTP [response](../index#res) argument to the middleware function, called "res" by convention. HTTP [request](../index#req) argument to the middleware function, called "req" by convention. |
Starting with Express 5, middleware functions that return a Promise will call `next(value)` when they reject or throw an error. `next` will be called with either the rejected value or the thrown Error.
Example
-------
Here is an example of a simple “Hello World” Express application. The remainder of this article will define and add three middleware functions to the application: one called `myLogger` that prints a simple log message, one called `requestTime` that displays the timestamp of the HTTP request, and one called `validateCookies` that validates incoming cookies.
```
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000)
```
### Middleware function myLogger
Here is a simple example of a middleware function called “myLogger”. This function just prints “LOGGED” when a request to the app passes through it. The middleware function is assigned to a variable named `myLogger`.
```
const myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
```
Notice the call above to `next()`. Calling this function invokes the next middleware function in the app. The `next()` function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The `next()` function could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention.
To load the middleware function, call `app.use()`, specifying the middleware function. For example, the following code loads the `myLogger` middleware function before the route to the root path (/).
```
const express = require('express')
const app = express()
const myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
app.use(myLogger)
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000)
```
Every time the app receives a request, it prints the message “LOGGED” to the terminal.
The order of middleware loading is important: middleware functions that are loaded first are also executed first.
If `myLogger` is loaded after the route to the root path, the request never reaches it and the app doesn’t print “LOGGED”, because the route handler of the root path terminates the request-response cycle.
The middleware function `myLogger` simply prints a message, then passes on the request to the next middleware function in the stack by calling the `next()` function.
### Middleware function requestTime
Next, we’ll create a middleware function called “requestTime” and add a property called `requestTime` to the request object.
```
const requestTime = function (req, res, next) {
req.requestTime = Date.now()
next()
}
```
The app now uses the `requestTime` middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to `req` (the request object).
```
const express = require('express')
const app = express()
const requestTime = function (req, res, next) {
req.requestTime = Date.now()
next()
}
app.use(requestTime)
app.get('/', (req, res) => {
let responseText = 'Hello World!<br>'
responseText += `<small>Requested at: ${req.requestTime}</small>`
res.send(responseText)
})
app.listen(3000)
```
When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.
### Middleware function validateCookies
Finally, we’ll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid.
Here’s an example function that validates cookies with an external async service.
```
async function cookieValidator (cookies) {
try {
await externallyValidateCookie(cookies.testCookie)
} catch {
throw new Error('Invalid cookies')
}
}
```
Here we use the [`cookie-parser`](https://expressjs.com/resources/middleware/cookie-parser.html) middleware to parse incoming cookies off the `req` object and pass them to our `cookieValidator` function. The `validateCookies` middleware returns a Promise that upon rejection will automatically trigger our error handler.
```
const express = require('express')
const cookieParser = require('cookie-parser')
const cookieValidator = require('./cookieValidator')
const app = express()
async function validateCookies (req, res, next) {
await cookieValidator(req.cookies)
next()
}
app.use(cookieParser())
app.use(validateCookies)
// error handler
app.use((err, req, res, next) => {
res.status(400).send(err.message)
})
app.listen(3000)
```
Note how `next()` is called after `await cookieValidator(req.cookies)`. This ensures that if `cookieValidator` resolves, the next middleware in the stack will get called. If you pass anything to the `next()` function (except the string `'route'` or `'router'`), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions.
Because you have access to the request object, the response object, the next middleware function in the stack, and the whole Node.js API, the possibilities with middleware functions are endless.
For more information about Express middleware, see: [Using Express middleware](using-middleware).
Configurable middleware
-----------------------
If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.
File: `my-middleware.js`
```
module.exports = function (options) {
return function (req, res, next) {
// Implement the middleware function based on the options object
next()
}
}
```
The middleware can now be used as shown below.
```
const mw = require('./my-middleware.js')
app.use(mw({ option1: '1', option2: '2' }))
```
Refer to [cookie-session](https://github.com/expressjs/cookie-session) and [compression](https://github.com/expressjs/compression) for examples of configurable middleware.
express Routing Routing
=======
*Routing* refers to how an application’s endpoints (URIs) respond to client requests. For an introduction to routing, see [Basic routing](../starter/basic-routing).
You define routing using methods of the Express `app` object that correspond to HTTP methods; for example, `app.get()` to handle GET requests and `app.post` to handle POST requests. For a full list, see [app.METHOD](../index#app.METHOD). You can also use [app.all()](../index#app.all) to handle all HTTP methods and [app.use()](../index#app.use) to specify middleware as the callback function (See [Using middleware](using-middleware) for details).
These routing methods specify a callback function (sometimes called “handler functions”) called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application “listens” for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.
In fact, the routing methods can have more than one callback function as arguments. With multiple callback functions, it is important to provide `next` as an argument to the callback function and then call `next()` within the body of the function to hand off control to the next callback.
The following code is an example of a very basic route.
```
const express = require('express')
const app = express()
// respond with "hello world" when a GET request is made to the homepage
app.get('/', (req, res) => {
res.send('hello world')
})
```
Route methods
-------------
A route method is derived from one of the HTTP methods, and is attached to an instance of the `express` class.
The following code is an example of routes that are defined for the GET and the POST methods to the root of the app.
```
// GET method route
app.get('/', (req, res) => {
res.send('GET request to the homepage')
})
// POST method route
app.post('/', (req, res) => {
res.send('POST request to the homepage')
})
```
Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on. For a full list, see [app.METHOD](../index#app.METHOD).
There is a special routing method, `app.all()`, used to load middleware functions at a path for *all* HTTP request methods. For example, the following handler is executed for requests to the route “/secret” whether using GET, POST, PUT, DELETE, or any other HTTP request method supported in the [http module](https://nodejs.org/api/http.html#http_http_methods).
```
app.all('/secret', (req, res, next) => {
console.log('Accessing the secret section ...')
next() // pass control to the next handler
})
```
Route paths
-----------
Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.
The characters `?`, `+`, `*`, and `()` are subsets of their regular expression counterparts. The hyphen (`-`) and the dot (`.`) are interpreted literally by string-based paths.
If you need to use the dollar character (`$`) in a path string, enclose it escaped within `([` and `])`. For example, the path string for requests at “`/data/$book`”, would be “`/data/([\$])book`”.
Express uses [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths. [Express Route Tester](http://forbeslindesay.github.io/express-route-tester/) is a handy tool for testing basic Express routes, although it does not support pattern matching.
Query strings are not part of the route path.
Here are some examples of route paths based on strings.
This route path will match requests to the root route, `/`.
```
app.get('/', (req, res) => {
res.send('root')
})
```
This route path will match requests to `/about`.
```
app.get('/about', (req, res) => {
res.send('about')
})
```
This route path will match requests to `/random.text`.
```
app.get('/random.text', (req, res) => {
res.send('random.text')
})
```
Here are some examples of route paths based on string patterns.
This route path will match `acd` and `abcd`.
```
app.get('/ab?cd', (req, res) => {
res.send('ab?cd')
})
```
This route path will match `abcd`, `abbcd`, `abbbcd`, and so on.
```
app.get('/ab+cd', (req, res) => {
res.send('ab+cd')
})
```
This route path will match `abcd`, `abxcd`, `abRANDOMcd`, `ab123cd`, and so on.
```
app.get('/ab*cd', (req, res) => {
res.send('ab*cd')
})
```
This route path will match `/abe` and `/abcde`.
```
app.get('/ab(cd)?e', (req, res) => {
res.send('ab(cd)?e')
})
```
Examples of route paths based on regular expressions:
This route path will match anything with an “a” in it.
```
app.get(/a/, (req, res) => {
res.send('/a/')
})
```
This route path will match `butterfly` and `dragonfly`, but not `butterflyman`, `dragonflyman`, and so on.
```
app.get(/.*fly$/, (req, res) => {
res.send('/.*fly$/')
})
```
### Route parameters
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the `req.params` object, with the name of the route parameter specified in the path as their respective keys.
```
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
```
To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.
```
app.get('/users/:userId/books/:bookId', (req, res) => {
res.send(req.params)
})
```
The name of route parameters must be made up of “word characters” ([A-Za-z0-9\_]).
Since the hyphen (`-`) and the dot (`.`) are interpreted literally, they can be used along with route parameters for useful purposes.
```
Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }
```
```
Route path: /plantae/:genus.:species
Request URL: http://localhost:3000/plantae/Prunus.persica
req.params: { "genus": "Prunus", "species": "persica" }
```
To have more control over the exact string that can be matched by a route parameter, you can append a regular expression in parentheses (`()`):
```
Route path: /user/:userId(\d+)
Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}
```
Because the regular expression is usually part of a literal string, be sure to escape any `\` characters with an additional backslash, for example `\\d+`.
In Express 4.x, [the `*` character in regular expressions is not interpreted in the usual way](https://github.com/expressjs/express/issues/2495). As a workaround, use `{0,}` instead of `*`. This will likely be fixed in Express 5.
Route handlers
--------------
You can provide multiple callback functions that behave like [middleware](using-middleware) to handle a request. The only exception is that these callbacks might invoke `next('route')` to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route.
Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples.
A single callback function can handle a route. For example:
```
app.get('/example/a', (req, res) => {
res.send('Hello from A!')
})
```
More than one callback function can handle a route (make sure you specify the `next` object). For example:
```
app.get('/example/b', (req, res, next) => {
console.log('the response will be sent by the next function ...')
next()
}, (req, res) => {
res.send('Hello from B!')
})
```
An array of callback functions can handle a route. For example:
```
const cb0 = function (req, res, next) {
console.log('CB0')
next()
}
const cb1 = function (req, res, next) {
console.log('CB1')
next()
}
const cb2 = function (req, res) {
res.send('Hello from C!')
}
app.get('/example/c', [cb0, cb1, cb2])
```
A combination of independent functions and arrays of functions can handle a route. For example:
```
const cb0 = function (req, res, next) {
console.log('CB0')
next()
}
const cb1 = function (req, res, next) {
console.log('CB1')
next()
}
app.get('/example/d', [cb0, cb1], (req, res, next) => {
console.log('the response will be sent by the next function ...')
next()
}, (req, res) => {
res.send('Hello from D!')
})
```
Response methods
----------------
The methods on the response object (`res`) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
| Method | Description |
| --- | --- |
| [res.download()](../index#res.download) | Prompt a file to be downloaded. |
| [res.end()](../index#res.end) | End the response process. |
| [res.json()](../index#res.json) | Send a JSON response. |
| [res.jsonp()](../index#res.jsonp) | Send a JSON response with JSONP support. |
| [res.redirect()](../index#res.redirect) | Redirect a request. |
| [res.render()](../index#res.render) | Render a view template. |
| [res.send()](../index#res.send) | Send a response of various types. |
| [res.sendFile()](../index#res.sendFile) | Send a file as an octet stream. |
| [res.sendStatus()](../index#res.sendStatus) | Set the response status code and send its string representation as the response body. |
app.route()
-----------
You can create chainable route handlers for a route path by using `app.route()`. Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: [Router() documentation](../index#router).
Here is an example of chained route handlers that are defined by using `app.route()`.
```
app.route('/book')
.get((req, res) => {
res.send('Get a random book')
})
.post((req, res) => {
res.send('Add a book')
})
.put((req, res) => {
res.send('Update the book')
})
```
express.Router
--------------
Use the `express.Router` class to create modular, mountable route handlers. A `Router` instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.
The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main app.
Create a router file named `birds.js` in the app directory, with the following content:
```
const express = require('express')
const router = express.Router()
// middleware that is specific to this router
router.use((req, res, next) => {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', (req, res) => {
res.send('Birds home page')
})
// define the about route
router.get('/about', (req, res) => {
res.send('About birds')
})
module.exports = router
```
Then, load the router module in the app:
```
const birds = require('./birds')
// ...
app.use('/birds', birds)
```
The app will now be able to handle requests to `/birds` and `/birds/about`, as well as call the `timeLog` middleware function that is specific to the route.
| programming_docs |
express Error Handling Error Handling
==============
*Error Handling* refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler so you don’t need to write your own to get started.
Catching Errors
---------------
It’s important to ensure that Express catches all errors that occur while running route handlers and middleware.
Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it. For example:
```
app.get('/', (req, res) => {
throw new Error('BROKEN') // Express will catch this on its own.
})
```
For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the `next()` function, where Express will catch and process them. For example:
```
app.get('/', (req, res, next) => {
fs.readFile('/file-does-not-exist', (err, data) => {
if (err) {
next(err) // Pass errors to Express.
} else {
res.send(data)
}
})
})
```
Starting with Express 5, route handlers and middleware that return a Promise will call `next(value)` automatically when they reject or throw an error. For example:
```
app.get('/user/:id', async (req, res, next) => {
const user = await getUserById(req.params.id)
res.send(user)
})
```
If `getUserById` throws an error or rejects, `next` will be called with either the thrown error or the rejected value. If no rejected value is provided, `next` will be called with a default Error object provided by the Express router.
If you pass anything to the `next()` function (except the string `'route'`), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions.
If the callback in a sequence provides no data, only errors, you can simplify this code as follows:
```
app.get('/', [
function (req, res, next) {
fs.writeFile('/inaccessible-path', 'data', next)
},
function (req, res) {
res.send('OK')
}
])
```
In the above example `next` is provided as the callback for `fs.writeFile`, which is called with or without errors. If there is no error the second handler is executed, otherwise Express catches and processes the error.
You must catch errors that occur in asynchronous code invoked by route handlers or middleware and pass them to Express for processing. For example:
```
app.get('/', (req, res, next) => {
setTimeout(() => {
try {
throw new Error('BROKEN')
} catch (err) {
next(err)
}
}, 100)
})
```
The above example uses a `try...catch` block to catch errors in the asynchronous code and pass them to Express. If the `try...catch` block were omitted, Express would not catch the error since it is not part of the synchronous handler code.
Use promises to avoid the overhead of the `try...catch` block or when using functions that return promises. For example:
```
app.get('/', (req, res, next) => {
Promise.resolve().then(() => {
throw new Error('BROKEN')
}).catch(next) // Errors will be passed to Express.
})
```
Since promises automatically catch both synchronous errors and rejected promises, you can simply provide `next` as the final catch handler and Express will catch errors, because the catch handler is given the error as the first argument.
You could also use a chain of handlers to rely on synchronous error catching, by reducing the asynchronous code to something trivial. For example:
```
app.get('/', [
function (req, res, next) {
fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => {
res.locals.data = data
next(err)
})
},
function (req, res) {
res.locals.data = res.locals.data.split(',')[1]
res.send(res.locals.data)
}
])
```
The above example has a couple of trivial statements from the `readFile` call. If `readFile` causes an error, then it passes the error to Express, otherwise you quickly return to the world of synchronous error handling in the next handler in the chain. Then, the example above tries to process the data. If this fails then the synchronous error handler will catch it. If you had done this processing inside the `readFile` callback then the application might exit and the Express error handlers would not run.
Whichever method you use, if you want Express error handlers to be called in and the application to survive, you must ensure that Express receives the error.
The default error handler
-------------------------
Express comes with a built-in error handler that takes care of any errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack.
If you pass an error to `next()` and you do not handle it in a custom error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace. The stack trace is not included in the production environment.
Set the environment variable `NODE_ENV` to `production`, to run the app in production mode.
When an error is written, the following information is added to the response:
* The `res.statusCode` is set from `err.status` (or `err.statusCode`). If this value is outside the 4xx or 5xx range, it will be set to 500.
* The `res.statusMessage` is set according to the status code.
* The body will be the HTML of the status code message when in production environment, otherwise will be `err.stack`.
* Any headers specified in an `err.headers` object.
If you call `next()` with an error after you have started writing the response (for example, if you encounter an error while streaming the response to the client) the Express default error handler closes the connection and fails the request.
So when you add a custom error handler, you must delegate to the default Express error handler, when the headers have already been sent to the client:
```
function errorHandler (err, req, res, next) {
if (res.headersSent) {
return next(err)
}
res.status(500)
res.render('error', { error: err })
}
```
Note that the default error handler can get triggered if you call `next()` with an error in your code more than once, even if custom error handling middleware is in place.
Writing error handlers
----------------------
Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: `(err, req, res, next)`. For example:
```
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
```
You define error-handling middleware last, after other `app.use()` and routes calls; for example:
```
const bodyParser = require('body-parser')
const methodOverride = require('method-override')
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json())
app.use(methodOverride())
app.use((err, req, res, next) => {
// logic
})
```
Responses from within a middleware function can be in any format, such as an HTML error page, a simple message, or a JSON string.
For organizational (and higher-level framework) purposes, you can define several error-handling middleware functions, much as you would with regular middleware functions. For example, to define an error-handler for requests made by using `XHR` and those without:
```
const bodyParser = require('body-parser')
const methodOverride = require('method-override')
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json())
app.use(methodOverride())
app.use(logErrors)
app.use(clientErrorHandler)
app.use(errorHandler)
```
In this example, the generic `logErrors` might write request and error information to `stderr`, for example:
```
function logErrors (err, req, res, next) {
console.error(err.stack)
next(err)
}
```
Also in this example, `clientErrorHandler` is defined as follows; in this case, the error is explicitly passed along to the next one.
Notice that when *not* calling “next” in an error-handling function, you are responsible for writing (and ending) the response. Otherwise those requests will “hang” and will not be eligible for garbage collection.
```
function clientErrorHandler (err, req, res, next) {
if (req.xhr) {
res.status(500).send({ error: 'Something failed!' })
} else {
next(err)
}
}
```
Implement the “catch-all” `errorHandler` function as follows (for example):
```
function errorHandler (err, req, res, next) {
res.status(500)
res.render('error', { error: err })
}
```
If you have a route handler with multiple callback functions you can use the `route` parameter to skip to the next route handler. For example:
```
app.get('/a_route_behind_paywall',
(req, res, next) => {
if (!req.user.hasPaid) {
// continue handling this request
next('route')
} else {
next()
}
}, (req, res, next) => {
PaidContent.find((err, doc) => {
if (err) return next(err)
res.json(doc)
})
})
```
In this example, the `getPaidContent` handler will be skipped but any remaining handlers in `app` for `/a_route_behind_paywall` would continue to be executed.
Calls to `next()` and `next(err)` indicate that the current handler is complete and in what state. `next(err)` will skip all remaining handlers in the chain except for those that are set up to handle errors as described above.
express Debugging Express Debugging Express
=================
Express uses the [debug](https://www.npmjs.com/package/debug) module internally to log information about route matches, middleware functions that are in use, application mode, and the flow of the request-response cycle.
`debug` is like an augmented version of `console.log`, but unlike `console.log`, you don’t have to comment out `debug` logs in production code. Logging is turned off by default and can be conditionally turned on by using the `DEBUG` environment variable.
To see all the internal logs used in Express, set the `DEBUG` environment variable to `express:*` when launching your app.
```
$ DEBUG=express:* node index.js
```
On Windows, use the corresponding command.
```
> set DEBUG=express:* & node index.js
```
Running this command on the default app generated by the [express generator](../starter/generator) prints the following output:
```
$ DEBUG=express:* node ./bin/www
express:router:route new / +0ms
express:router:layer new / +1ms
express:router:route get / +1ms
express:router:layer new / +0ms
express:router:route new / +1ms
express:router:layer new / +0ms
express:router:route get / +0ms
express:router:layer new / +0ms
express:application compile etag weak +1ms
express:application compile query parser extended +0ms
express:application compile trust proxy false +0ms
express:application booting in development mode +1ms
express:router use / query +0ms
express:router:layer new / +0ms
express:router use / expressInit +0ms
express:router:layer new / +0ms
express:router use / favicon +1ms
express:router:layer new / +0ms
express:router use / logger +0ms
express:router:layer new / +0ms
express:router use / jsonParser +0ms
express:router:layer new / +1ms
express:router use / urlencodedParser +0ms
express:router:layer new / +0ms
express:router use / cookieParser +0ms
express:router:layer new / +0ms
express:router use / stylus +90ms
express:router:layer new / +0ms
express:router use / serveStatic +0ms
express:router:layer new / +0ms
express:router use / router +0ms
express:router:layer new / +1ms
express:router use /users router +0ms
express:router:layer new /users +0ms
express:router use / <anonymous> +0ms
express:router:layer new / +0ms
express:router use / <anonymous> +0ms
express:router:layer new / +0ms
express:router use / <anonymous> +0ms
express:router:layer new / +0ms
```
When a request is then made to the app, you will see the logs specified in the Express code:
```
express:router dispatching GET / +4h
express:router query : / +2ms
express:router expressInit : / +0ms
express:router favicon : / +0ms
express:router logger : / +1ms
express:router jsonParser : / +0ms
express:router urlencodedParser : / +1ms
express:router cookieParser : / +0ms
express:router stylus : / +0ms
express:router serveStatic : / +2ms
express:router router : / +2ms
express:router dispatching GET / +1ms
express:view lookup "index.pug" +338ms
express:view stat "/projects/example/views/index.pug" +0ms
express:view render "/projects/example/views/index.pug" +1ms
```
To see the logs only from the router implementation set the value of `DEBUG` to `express:router`. Likewise, to see logs only from the application implementation set the value of `DEBUG` to `express:application`, and so on.
Applications generated by `express`
-----------------------------------
An application generated by the `express` command also uses the `debug` module and its debug namespace is scoped to the name of the application.
For example, if you generated the app with `$ express sample-app`, you can enable the debug statements with the following command:
```
$ DEBUG=sample-app:* node ./bin/www
```
You can specify more than one debug namespace by assigning a comma-separated list of names:
```
$ DEBUG=http,mail,express:* node index.js
```
Advanced options
----------------
When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging:
| Name | Purpose |
| --- | --- |
| `DEBUG` | Enables/disables specific debugging namespaces. |
| `DEBUG_COLORS` | Whether or not to use colors in the debug output. |
| `DEBUG_DEPTH` | Object inspection depth. |
| `DEBUG_FD` | File descriptor to write debug output to. |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
**Note:** The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list.
Resources
---------
For more information about `debug`, see the [debug](https://www.npmjs.com/package/debug).
express Moving to Express 5 Moving to Express 5
===================
Overview
--------
Express 5.0 is still in the beta release stage, but here is a preview of the changes that will be in the release and how to migrate your Express 4 app to Express 5.
To install the latest beta and to preview Express 5, enter the following command in your application root directory:
```
$ npm install "express@>=5.0.0-beta.1" --save
```
You can then run your automated tests to see what fails, and fix problems according to the updates listed below. After addressing test failures, run your app to see what errors occur. You’ll find out right away if the app uses any methods or properties that are not supported.
Changes in Express 5
--------------------
**Removed methods and properties**
* [app.del()](#app.del)
* [app.param(fn)](#app.param)
* [Pluralized method names](#plural)
* [Leading colon in name argument to app.param(name, fn)](#leading)
* [req.param(name)](#req.param)
* [res.json(obj, status)](#res.json)
* [res.jsonp(obj, status)](#res.jsonp)
* [res.send(body, status)](#res.send.body)
* [res.send(status)](#res.send.status)
* [res.sendfile()](#res.sendfile)
**Changed**
* [Path route matching syntax](#path-syntax)
* [Rejected promises handled from middleware and handlers](#rejected-promises)
* [app.router](#app.router)
* [req.host](#req.host)
* [req.query](#req.query)
**Improvements**
* [res.render()](#res.render)
### Removed methods and properties
If you use any of these methods or properties in your app, it will crash. So, you’ll need to change your app after you update to version 5.
#### app.del()
Express 5 no longer supports the `app.del()` function. If you use this function an error is thrown. For registering HTTP DELETE routes, use the `app.delete()` function instead.
Initially `del` was used instead of `delete`, because `delete` is a reserved keyword in JavaScript. However, as of ECMAScript 6, `delete` and other reserved keywords can legally be used as property names.
#### app.param(fn)
The `app.param(fn)` signature was used for modifying the behavior of the `app.param(name, fn)` function. It has been deprecated since v4.11.0, and Express 5 no longer supports it at all.
#### Pluralized method names
The following method names have been pluralized. In Express 4, using the old methods resulted in a deprecation warning. Express 5 no longer supports them at all:
`req.acceptsCharset()` is replaced by `req.acceptsCharsets()`.
`req.acceptsEncoding()` is replaced by `req.acceptsEncodings()`.
`req.acceptsLanguage()` is replaced by `req.acceptsLanguages()`.
#### Leading colon (:) in the name for app.param(name, fn)
A leading colon character (:) in the name for the `app.param(name, fn)` function is a remnant of Express 3, and for the sake of backwards compatibility, Express 4 supported it with a deprecation notice. Express 5 will silently ignore it and use the name parameter without prefixing it with a colon.
This should not affect your code if you follow the Express 4 documentation of [app.param](../index#app.param), as it makes no mention of the leading colon.
#### req.param(name)
This potentially confusing and dangerous method of retrieving form data has been removed. You will now need to specifically look for the submitted parameter name in the `req.params`, `req.body`, or `req.query` object.
#### res.json(obj, status)
Express 5 no longer supports the signature `res.json(obj, status)`. Instead, set the status and then chain it to the `res.json()` method like this: `res.status(status).json(obj)`.
#### res.jsonp(obj, status)
Express 5 no longer supports the signature `res.jsonp(obj, status)`. Instead, set the status and then chain it to the `res.jsonp()` method like this: `res.status(status).jsonp(obj)`.
#### res.send(body, status)
Express 5 no longer supports the signature `res.send(obj, status)`. Instead, set the status and then chain it to the `res.send()` method like this: `res.status(status).send(obj)`.
#### res.send(status)
Express 5 no longer supports the signature `res.send(*status*)`, where *`status`* is a number. Instead, use the `res.sendStatus(statusCode)` function, which sets the HTTP response header status code and sends the text version of the code: “Not Found”, “Internal Server Error”, and so on. If you need to send a number by using the `res.send()` function, quote the number to convert it to a string, so that Express does not interpret it as an attempt to use the unsupported old signature.
#### res.sendfile()
The `res.sendfile()` function has been replaced by a camel-cased version `res.sendFile()` in Express 5.
### Changed
#### Path route matching syntax
Path route matching syntax is when a string is supplied as the first parameter to the `app.all()`, `app.use()`, `app.METHOD()`, `router.all()`, `router.METHOD()`, and `router.use()` APIs. The following changes have been made to how the path string is matched to an incoming request:
* Add new `?`, `*`, and `+` parameter modifiers.
* Matching group expressions are only RegExp syntax.
+ `(*)` is no longer valid and must be written as `(.*)`, for example.
* Named matching groups no longer available by position in `req.params`.
+ `/:foo(.*)` only captures as `req.params.foo` and not available as `req.params[0]`.
* Regular expressions can only be used in a matching group.
+ `/\\d+` is no longer valid and must be written as `/(\\d+)`.
* Special `*` path segment behavior removed.
+ `/foo/*/bar` will match a literal `*` as the middle segment.
#### Rejected promises handled from middleware and handlers
Request middleware and handlers that return rejected promises are now handled by forwarding the rejected value as an `Error` to the error handling middleware. This means that using `async` functions as middleware and handlers are easier than ever. When an error is thrown in an `async` function or a rejected promise is `await`ed inside an async function, those errors will be passed to the error handler as if calling `next(err)`.
Details of how Express handles errors is covered in the [error handling documentation](error-handling).
#### app.router
The `app.router` object, which was removed in Express 4, has made a comeback in Express 5. In the new version, this object is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it.
#### req.host
In Express 4, the `req.host` function incorrectly stripped off the port number if it was present. In Express 5 the port number is maintained.
#### req.query
The `req.query` property is no longer a writable property and is instead a getter. The default query parser has been changed from “extended” to “simple”.
### Improvements
#### res.render()
This method now enforces asynchronous behavior for all view engines, avoiding bugs caused by view engines that had a synchronous implementation and that violated the recommended interface.
| programming_docs |
express Express behind proxies Express behind proxies
======================
When running an Express app behind a reverse proxy, some of the Express APIs may return different values than expected. In order to adjust for this, the `trust proxy` application setting may be used to expose information provided by the reverse proxy in the Express APIs. The most common issue is express APIs that expose the client’s IP address may instead show an internal IP address of the reverse proxy.
When configuring the `trust proxy` setting, it is important to understand the exact setup of the reverse proxy. Since this setting will trust values provided in the request, it is important that the combination of the setting in Express matches how the reverse proxy operates.
The application setting `trust proxy` may be set to one of the values listed in the following table.
| Type | Value |
| --- | --- |
| Boolean | If `true`, the client’s IP address is understood as the left-most entry in the `X-Forwarded-For` header. If `false`, the app is understood as directly facing the client and the client’s IP address is derived from `req.socket.remoteAddress`. This is the default setting. When setting to `true`, it is important to ensure that the last reverse proxy trusted is removing/overwriting all of the following HTTP headers: `X-Forwarded-For`, `X-Forwarded-Host`, and `X-Forwarded-Proto` otherwise it may be possible for the client to provide any value. |
| IP addresses | An IP address, subnet, or an array of IP addresses and subnets to trust as being a reverse proxy. The following list shows the pre-configured subnet names:* loopback - `127.0.0.1/8`, `::1/128`
* linklocal - `169.254.0.0/16`, `fe80::/10`
* uniquelocal - `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `fc00::/7`
You can set IP addresses in any of the following ways:
```
app.set('trust proxy', 'loopback') // specify a single subnet
app.set('trust proxy', 'loopback, 123.123.123.123') // specify a subnet and an address
app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple subnets as CSV
app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array
```
When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client’s IP address. This works by checking if `req.socket.remoteAddress` is trusted. If so, then each address in `X-Forwarded-For` is checked from right to left until the first non-trusted address. |
| Number | Use the address that is at most `n` number of hops away from the Express application. `req.socket.remoteAddress` is the first hop, and the rest are looked for in the `X-Forwarded-For` header from right to left. A value of `0` means that the first untrusted address would be `req.socket.remoteAddress`, i.e. there is no reverse proxy. When using this setting, it is important to ensure there are not multiple, different-length paths to the Express application such that the client can be less than the configured number of hops away, otherwise it may be possible for the client to provide any value. |
| Function | Custom trust implementation.
```
app.set('trust proxy', (ip) => {
if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs
else return false
})
```
|
Enabling `trust proxy` will have the following impact:
* The value of [req.hostname](https://expressjs.com/en/api.html#req.hostname) is derived from the value set in the `X-Forwarded-Host` header, which can be set by the client or by the proxy.
* `X-Forwarded-Proto` can be set by the reverse proxy to tell the app whether it is `https` or `http` or even an invalid name. This value is reflected by [req.protocol](https://expressjs.com/en/api.html#req.protocol).
* The [req.ip](https://expressjs.com/en/api.html#req.ip) and [req.ips](https://expressjs.com/en/api.html#req.ips) values are populated based on the socket address and `X-Forwarded-For` header, starting at the first untrusted address.
The `trust proxy` setting is implemented using the [proxy-addr](https://www.npmjs.com/package/proxy-addr) package. For more information, see its documentation.
express Moving to Express 4 Moving to Express 4
===================
Overview
--------
Express 4 is a breaking change from Express 3. That means an existing Express 3 app will *not* work if you update the Express version in its dependencies.
This article covers:
* [Changes in Express 4](#changes).
* [An example](#example-migration) of migrating an Express 3 app to Express 4.
* [Upgrading to the Express 4 app generator](#app-gen).
Changes in Express 4
--------------------
There are several significant changes in Express 4:
* [Changes to Express core and middleware system.](#core-changes) The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
* [Changes to the routing system.](#routing)
* [Various other changes.](#other-changes)
See also:
* [New features in 4.x.](https://github.com/expressjs/express/wiki/New-features-in-4.x)
* [Migrating from 3.x to 4.x.](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x)
### Changes to Express core and middleware system
Express 4 no longer depends on Connect, and removes all built-in middleware from its core, except for the `express.static` function. This means that Express is now an independent routing and middleware web framework, and Express versioning and releases are not affected by middleware updates.
Without built-in middleware, you must explicitly add all the middleware that is required to run your app. Simply follow these steps:
1. Install the module: `npm install --save <module-name>`
2. In your app, require the module: `require('module-name')`
3. Use the module according to its documentation: `app.use( ... )`
The following table lists Express 3 middleware and their counterparts in Express 4.
| Express 3 | Express 4 |
| --- | --- |
| `express.bodyParser` | [body-parser](https://github.com/expressjs/body-parser) + [multer](https://github.com/expressjs/multer) |
| `express.compress` | [compression](https://github.com/expressjs/compression) |
| `express.cookieSession` | [cookie-session](https://github.com/expressjs/cookie-session) |
| `express.cookieParser` | [cookie-parser](https://github.com/expressjs/cookie-parser) |
| `express.logger` | [morgan](https://github.com/expressjs/morgan) |
| `express.session` | [express-session](https://github.com/expressjs/session) |
| `express.favicon` | [serve-favicon](https://github.com/expressjs/serve-favicon) |
| `express.responseTime` | [response-time](https://github.com/expressjs/response-time) |
| `express.errorHandler` | [errorhandler](https://github.com/expressjs/errorhandler) |
| `express.methodOverride` | [method-override](https://github.com/expressjs/method-override) |
| `express.timeout` | [connect-timeout](https://github.com/expressjs/timeout) |
| `express.vhost` | [vhost](https://github.com/expressjs/vhost) |
| `express.csrf` | [csurf](https://github.com/expressjs/csurf) |
| `express.directory` | [serve-index](https://github.com/expressjs/serve-index) |
| `express.static` | [serve-static](https://github.com/expressjs/serve-static) |
Here is the [complete list](https://github.com/senchalabs/connect#middleware) of Express 4 middleware.
In most cases, you can simply replace the old version 3 middleware with its Express 4 counterpart. For details, see the module documentation in GitHub.
####
`app.use` accepts parameters
In version 4 you can use a variable parameter to define the path where middleware functions are loaded, then read the value of the parameter from the route handler. For example:
```
app.use('/book/:id', (req, res, next) => {
console.log('ID:', req.params.id)
next()
})
```
### The routing system
Apps now implicitly load routing middleware, so you no longer have to worry about the order in which middleware is loaded with respect to the `router` middleware.
The way you define routes is unchanged, but the routing system has two new features to help organize your routes:
* A new method, `app.route()`, to create chainable route handlers for a route path.
* A new class, `express.Router`, to create modular mountable route handlers.
####
`app.route()` method
The new `app.route()` method enables you to create chainable route handlers for a route path. Because the path is specified in a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see [`Router()` documentation](../index#router).
Here is an example of chained route handlers that are defined by using the `app.route()` function.
```
app.route('/book')
.get((req, res) => {
res.send('Get a random book')
})
.post((req, res) => {
res.send('Add a book')
})
.put((req, res) => {
res.send('Update the book')
})
```
####
`express.Router` class
The other feature that helps to organize routes is a new class, `express.Router`, that you can use to create modular mountable route handlers. A `Router` instance is a complete middleware and routing system; for this reason it is often referred to as a “mini-app”.
The following example creates a router as a module, loads middleware in it, defines some routes, and mounts it on a path on the main app.
For example, create a router file named `birds.js` in the app directory, with the following content:
```
var express = require('express')
var router = express.Router()
// middleware specific to this router
router.use((req, res, next) => {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', (req, res) => {
res.send('Birds home page')
})
// define the about route
router.get('/about', (req, res) => {
res.send('About birds')
})
module.exports = router
```
Then, load the router module in the app:
```
var birds = require('./birds')
// ...
app.use('/birds', birds)
```
The app will now be able to handle requests to the `/birds` and `/birds/about` paths, and will call the `timeLog` middleware that is specific to the route.
### Other changes
The following table lists other small but important changes in Express 4:
| Object | Description |
| --- | --- |
| Node.js | Express 4 requires Node.js 0.10.x or later and has dropped support for Node.js 0.8.x. |
| `http.createServer()` | The `http` module is no longer needed, unless you need to directly work with it (socket.io/SPDY/HTTPS). The app can be started by using the `app.listen()` function. |
| `app.configure()` | The `app.configure()` function has been removed. Use the `process.env.NODE_ENV` or `app.get('env')` function to detect the environment and configure the app accordingly. |
| `json spaces` | The `json spaces` application property is disabled by default in Express 4. |
| `req.accepted()` | Use `req.accepts()`, `req.acceptsEncodings()`, `req.acceptsCharsets()`, and `req.acceptsLanguages()`. |
| `res.location()` | No longer resolves relative URLs. |
| `req.params` | Was an array; now an object. |
| `res.locals` | Was a function; now an object. |
| `res.headerSent` | Changed to `res.headersSent`. |
| `app.route` | Now available as `app.mountpath`. |
| `res.on('header')` | Removed. |
| `res.charset` | Removed. |
| `res.setHeader('Set-Cookie', val)` | Functionality is now limited to setting the basic cookie value. Use `res.cookie()` for added functionality. |
Example app migration
---------------------
Here is an example of migrating an Express 3 application to Express 4. The files of interest are `app.js` and `package.json`.
### Version 3 app
#### `app.js`
Consider an Express v.3 application with the following `app.js` file:
```
var express = require('express')
var routes = require('./routes')
var user = require('./routes/user')
var http = require('http')
var path = require('path')
var app = express()
// all environments
app.set('port', process.env.PORT || 3000)
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(express.favicon())
app.use(express.logger('dev'))
app.use(express.methodOverride())
app.use(express.session({ secret: 'your secret here' }))
app.use(express.bodyParser())
app.use(app.router)
app.use(express.static(path.join(__dirname, 'public')))
// development only
if (app.get('env') === 'development') {
app.use(express.errorHandler())
}
app.get('/', routes.index)
app.get('/users', user.list)
http.createServer(app).listen(app.get('port'), () => {
console.log('Express server listening on port ' + app.get('port'))
})
```
#### `package.json`
The accompanying version 3 `package.json` file might look something like this:
```
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.12.0",
"pug": "*"
}
}
```
### Process
Begin the migration process by installing the required middleware for the Express 4 app and updating Express and Pug to their respective latest version with the following command:
```
$ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest pug@latest --save
```
Make the following changes to `app.js`:
1. The built-in Express middleware functions `express.favicon`, `express.logger`, `express.methodOverride`, `express.session`, `express.bodyParser` and `express.errorHandler` are no longer available on the `express` object. You must install their alternatives manually and load them in the app.
2. You no longer need to load the `app.router` function. It is not a valid Express 4 app object, so remove the `app.use(app.router);` code.
3. Make sure that the middleware functions are loaded in the correct order - load `errorHandler` after loading the app routes.
### Version 4 app
#### `package.json`
Running the above `npm` command will update `package.json` as follows:
```
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"body-parser": "^1.5.2",
"errorhandler": "^1.1.1",
"express": "^4.8.0",
"express-session": "^1.7.2",
"pug": "^2.0.0",
"method-override": "^2.1.2",
"morgan": "^1.2.2",
"multer": "^0.1.3",
"serve-favicon": "^2.0.1"
}
}
```
#### `app.js`
Then, remove invalid code, load the required middleware, and make other changes as necessary. The `app.js` file will look like this:
```
var http = require('http')
var express = require('express')
var routes = require('./routes')
var user = require('./routes/user')
var path = require('path')
var favicon = require('serve-favicon')
var logger = require('morgan')
var methodOverride = require('method-override')
var session = require('express-session')
var bodyParser = require('body-parser')
var multer = require('multer')
var errorHandler = require('errorhandler')
var app = express()
// all environments
app.set('port', process.env.PORT || 3000)
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(favicon(path.join(__dirname, '/public/favicon.ico')))
app.use(logger('dev'))
app.use(methodOverride())
app.use(session({
resave: true,
saveUninitialized: true,
secret: 'uwotm8'
}))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(multer())
app.use(express.static(path.join(__dirname, 'public')))
app.get('/', routes.index)
app.get('/users', user.list)
// error handling middleware should be loaded after the loading the routes
if (app.get('env') === 'development') {
app.use(errorHandler())
}
var server = http.createServer(app)
server.listen(app.get('port'), () => {
console.log('Express server listening on port ' + app.get('port'))
})
```
Unless you need to work directly with the `http` module (socket.io/SPDY/HTTPS), loading it is not required, and the app can be simply started this way:
```
app.listen(app.get('port'), () => {
console.log('Express server listening on port ' + app.get('port'))
})
```
### Run the app
The migration process is complete, and the app is now an Express 4 app. To confirm, start the app by using the following command:
```
$ node .
```
Load <http://localhost:3000> and see the home page being rendered by Express 4.
Upgrading to the Express 4 app generator
----------------------------------------
The command-line tool to generate an Express app is still `express`, but to upgrade to the new version, you must uninstall the Express 3 app generator and then install the new `express-generator`.
### Installing
If you already have the Express 3 app generator installed on your system, you must uninstall it:
```
$ npm uninstall -g express
```
Depending on how your file and directory privileges are configured, you might need to run this command with `sudo`.
Now install the new generator:
```
$ npm install -g express-generator
```
Depending on how your file and directory privileges are configured, you might need to run this command with `sudo`.
Now the `express` command on your system is updated to the Express 4 generator.
### Changes to the app generator
Command options and use largely remain the same, with the following exceptions:
* Removed the `--sessions` option.
* Removed the `--jshtml` option.
* Added the `--hogan` option to support [Hogan.js](http://twitter.github.io/hogan.js/).
### Example
Execute the following command to create an Express 4 app:
```
$ express app4
```
If you look at the contents of the `app4/app.js` file, you will notice that all the middleware functions (except `express.static`) that are required for the app are loaded as independent modules, and the `router` middleware is no longer explicitly loaded in the app.
You will also notice that the `app.js` file is now a Node.js module, in contrast to the standalone app that was generated by the old generator.
After installing the dependencies, start the app by using the following command:
```
$ npm start
```
If you look at the npm start script in the `package.json` file, you will notice that the actual command that starts the app is `node ./bin/www`, which used to be `node app.js` in Express 3.
Because the `app.js` file that was generated by the Express 4 generator is now a Node.js module, it can no longer be started independently as an app (unless you modify the code). The module must be loaded in a Node.js file and started via the Node.js file. The Node.js file is `./bin/www` in this case.
Neither the `bin` directory nor the extensionless `www` file is mandatory for creating an Express app or starting the app. They are just suggestions made by the generator, so feel free to modify them to suit your needs.
To get rid of the `www` directory and keep things the “Express 3 way”, delete the line that says `module.exports = app;` at the end of the `app.js` file, then paste the following code in its place:
```
app.set('port', process.env.PORT || 3000)
var server = app.listen(app.get('port'), () => {
debug('Express server listening on port ' + server.address().port)
})
```
Ensure that you load the `debug` module at the top of the `app.js` file by using the following code:
```
var debug = require('debug')('app4')
```
Next, change `"start": "node ./bin/www"` in the `package.json` file to `"start": "node app.js"`.
You have now moved the functionality of `./bin/www` back to `app.js`. This change is not recommended, but the exercise helps you to understand how the `./bin/www` file works, and why the `app.js` file no longer starts on its own.
express Using middleware Using middleware
================
Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.
*Middleware* functions are functions that have access to the [request object](../index#req) (`req`), the [response object](../index#res) (`res`), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named `next`.
Middleware functions can perform the following tasks:
* Execute any code.
* Make changes to the request and the response objects.
* End the request-response cycle.
* Call the next middleware function in the stack.
If the current middleware function does not end the request-response cycle, it must call `next()` to pass control to the next middleware function. Otherwise, the request will be left hanging.
An Express application can use the following types of middleware:
* [Application-level middleware](#middleware.application)
* [Router-level middleware](#middleware.router)
* [Error-handling middleware](#middleware.error-handling)
* [Built-in middleware](#middleware.built-in)
* [Third-party middleware](#middleware.third-party)
You can load application-level and router-level middleware with an optional mount path. You can also load a series of middleware functions together, which creates a sub-stack of the middleware system at a mount point.
Application-level middleware
----------------------------
Bind application-level middleware to an instance of the [app object](../index#app) by using the `app.use()` and `app.METHOD()` functions, where `METHOD` is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
```
const express = require('express')
const app = express()
app.use((req, res, next) => {
console.log('Time:', Date.now())
next()
})
```
This example shows a middleware function mounted on the `/user/:id` path. The function is executed for any type of HTTP request on the `/user/:id` path.
```
app.use('/user/:id', (req, res, next) => {
console.log('Request Type:', req.method)
next()
})
```
This example shows a route and its handler function (middleware system). The function handles GET requests to the `/user/:id` path.
```
app.get('/user/:id', (req, res, next) => {
res.send('USER')
})
```
Here is an example of loading a series of middleware functions at a mount point, with a mount path. It illustrates a middleware sub-stack that prints request info for any type of HTTP request to the `/user/:id` path.
```
app.use('/user/:id', (req, res, next) => {
console.log('Request URL:', req.originalUrl)
next()
}, (req, res, next) => {
console.log('Request Type:', req.method)
next()
})
```
Route handlers enable you to define multiple routes for a path. The example below defines two routes for GET requests to the `/user/:id` path. The second route will not cause any problems, but it will never get called because the first route ends the request-response cycle.
This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
```
app.get('/user/:id', (req, res, next) => {
console.log('ID:', req.params.id)
next()
}, (req, res, next) => {
res.send('User Info')
})
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', (req, res, next) => {
res.send(req.params.id)
})
```
To skip the rest of the middleware functions from a router middleware stack, call `next('route')` to pass control to the next route. **NOTE**: `next('route')` will work only in middleware functions that were loaded by using the `app.METHOD()` or `router.METHOD()` functions.
This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
```
app.get('/user/:id', (req, res, next) => {
// if the user ID is 0, skip to the next route
if (req.params.id === '0') next('route')
// otherwise pass the control to the next middleware function in this stack
else next()
}, (req, res, next) => {
// send a regular response
res.send('regular')
})
// handler for the /user/:id path, which sends a special response
app.get('/user/:id', (req, res, next) => {
res.send('special')
})
```
Middleware can also be declared in an array for reusability.
This example shows an array with a middleware sub-stack that handles GET requests to the `/user/:id` path
```
function logOriginalUrl (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}
function logMethod (req, res, next) {
console.log('Request Type:', req.method)
next()
}
const logStuff = [logOriginalUrl, logMethod]
app.get('/user/:id', logStuff, (req, res, next) => {
res.send('User Info')
})
```
Router-level middleware
-----------------------
Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of `express.Router()`.
```
const router = express.Router()
```
Load router-level middleware by using the `router.use()` and `router.METHOD()` functions.
The following example code replicates the middleware system that is shown above for application-level middleware, by using router-level middleware:
```
const express = require('express')
const app = express()
const router = express.Router()
// a middleware function with no mount path. This code is executed for every request to the router
router.use((req, res, next) => {
console.log('Time:', Date.now())
next()
})
// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
router.use('/user/:id', (req, res, next) => {
console.log('Request URL:', req.originalUrl)
next()
}, (req, res, next) => {
console.log('Request Type:', req.method)
next()
})
// a middleware sub-stack that handles GET requests to the /user/:id path
router.get('/user/:id', (req, res, next) => {
// if the user ID is 0, skip to the next router
if (req.params.id === '0') next('route')
// otherwise pass control to the next middleware function in this stack
else next()
}, (req, res, next) => {
// render a regular page
res.render('regular')
})
// handler for the /user/:id path, which renders a special page
router.get('/user/:id', (req, res, next) => {
console.log(req.params.id)
res.render('special')
})
// mount the router on the app
app.use('/', router)
```
To skip the rest of the router’s middleware functions, call `next('router')` to pass control back out of the router instance.
This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
```
const express = require('express')
const app = express()
const router = express.Router()
// predicate the router with a check and bail out when needed
router.use((req, res, next) => {
if (!req.headers['x-auth']) return next('router')
next()
})
router.get('/user/:id', (req, res) => {
res.send('hello, user!')
})
// use the router and 401 anything falling through
app.use('/admin', router, (req, res) => {
res.sendStatus(401)
})
```
Error-handling middleware
-------------------------
Error-handling middleware always takes *four* arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the `next` object, you must specify it to maintain the signature. Otherwise, the `next` object will be interpreted as regular middleware and will fail to handle errors.
Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`):
```
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
```
For details about error-handling middleware, see: [Error handling](error-handling).
Built-in middleware
-------------------
Starting with version 4.x, Express no longer depends on [Connect](https://github.com/senchalabs/connect). The middleware functions that were previously included with Express are now in separate modules; see [the list of middleware functions](https://github.com/senchalabs/connect#middleware).
Express has the following built-in middleware functions:
* [express.static](../index#express.static) serves static assets such as HTML files, images, and so on.
* [express.json](../index#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+**
* [express.urlencoded](../index#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**
Third-party middleware
----------------------
Use third-party middleware to add functionality to Express apps.
Install the Node.js module for the required functionality, then load it in your app at the application level or at the router level.
The following example illustrates installing and loading the cookie-parsing middleware function `cookie-parser`.
```
$ npm install cookie-parser
```
```
const express = require('express')
const app = express()
const cookieParser = require('cookie-parser')
// load the cookie-parsing middleware
app.use(cookieParser())
```
For a partial list of third-party middleware functions that are commonly used with Express, see: [Third-party middleware](https://expressjs.com/en/resources/middleware.html).
| programming_docs |
express Using template engines with Express Using template engines with Express
===================================
A *template engine* enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
Some popular template engines that work with Express are [Pug](https://pugjs.org/api/getting-started.html), [Mustache](https://www.npmjs.com/package/mustache), and [EJS](https://www.npmjs.com/package/ejs). The [Express application generator](../starter/generator) uses [Jade](https://www.npmjs.com/package/jade) as its default, but it also supports several others.
See [Template Engines (Express wiki)](https://github.com/expressjs/express/wiki#template-engines) for a list of template engines you can use with Express. See also [Comparing JavaScript Templating Engines: Jade, Mustache, Dust and More](https://strongloop.com/strongblog/compare-javascript-templates-jade-mustache-dust/).
**Note**: Jade has been renamed to [Pug](https://www.npmjs.com/package/pug). You can continue to use Jade in your app, and it will work just fine. However if you want the latest updates to the template engine, you must replace Jade with Pug in your app.
To render template files, set the following [application setting properties](../index#app.set), set in `app.js` in the default app created by the generator:
* `views`, the directory where the template files are located. Eg: `app.set('views', './views')`. This defaults to the `views` directory in the application root directory.
* `view engine`, the template engine to use. For example, to use the Pug template engine: `app.set('view engine', 'pug')`.
Then install the corresponding template engine npm package; for example to install Pug:
```
$ npm install pug --save
```
Express-compliant template engines such as Jade and Pug export a function named `__express(filePath, options, callback)`, which is called by the `res.render()` function to render the template code.
Some template engines do not follow this convention. The [Consolidate.js](https://www.npmjs.org/package/consolidate) library follows this convention by mapping all of the popular Node.js template engines, and therefore works seamlessly within Express.
After the view engine is set, you don’t have to specify the engine or load the template engine module in your app; Express loads the module internally, as shown below (for the above example).
```
app.set('view engine', 'pug')
```
Create a Pug template file named `index.pug` in the `views` directory, with the following content:
```
html
head
title= title
body
h1= message
```
Then create a route to render the `index.pug` file. If the `view engine` property is not set, you must specify the extension of the `view` file. Otherwise, you can omit it.
```
app.get('/', (req, res) => {
res.render('index', { title: 'Hey', message: 'Hello there!' })
})
```
When you make a request to the home page, the `index.pug` file will be rendered as HTML.
Note: The view engine cache does not cache the contents of the template’s output, only the underlying template itself. The view is still re-rendered with every request even when the cache is on.
To learn more about how template engines work in Express, see: [“Developing template engines for Express”](../advanced/developing-template-engines).
express Overriding the Express API Overriding the Express API
==========================
The Express API consists of various methods and properties on the request and response objects. These are inherited by prototype. There are two extension points for the Express API:
1. The global prototypes at `express.request` and `express.response`.
2. App-specific prototypes at `app.request` and `app.response`.
Altering the global prototypes will affect all loaded Express apps in the same process. If desired, alterations can be made app-specific by only altering the app-specific prototypes after creating a new app.
Methods
-------
You can override the signature and behavior of existing methods with your own, by assigning a custom function.
Following is an example of overriding the behavior of [res.sendStatus](https://expressjs.com/index.html#res.sendStatus).
```
app.response.sendStatus = function (statusCode, type, message) {
// code is intentionally kept simple for demonstration purpose
return this.contentType(type)
.status(statusCode)
.send(message)
}
```
The above implementation completely changes the original signature of `res.sendStatus`. It now accepts a status code, encoding type, and the message to be sent to the client.
The overridden method may now be used this way:
```
res.sendStatus(404, 'application/json', '{"error":"resource not found"}')
```
Properties
----------
Properties in the Express API are either:
1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`)
2. Defined as getters (ex: `req.secure`, `req.ip`)
Since properties under category 1 are dynamically assigned on the `request` and `response` objects in the context of the current request-response cycle, their behavior cannot be overridden.
Properties under category 2 can be overwritten using the Express API extensions API.
The following code rewrites how the value of `req.ip` is to be derived. Now, it simply returns the value of the `Client-IP` request header.
```
Object.defineProperty(app.request, 'ip', {
configurable: true,
enumerable: true,
get () { return this.get('Client-IP') }
})
```
Prototype
---------
In order to provide the Express.js API, the request/response obects passed to Express.js (via `app(req, res)`, for example) need to inherit from the same prototype chain. By default this is `http.IncomingRequest.prototype` for the request and `http.ServerResponse.prototype` for the response.
Unless necessary, it is recommended that this be done only at the application level, rather than globally. Also, take care that the prototype that is being used matches the functionality as closely as possible to the default prototypes.
```
// Use FakeRequest and FakeResponse in place of http.IncomingRequest and http.ServerResponse
// for the given app reference
Object.setPrototypeOf(Object.getPrototypeOf(app.request), FakeRequest.prototype)
Object.setPrototypeOf(Object.getPrototypeOf(app.response), FakeResponse.prototype)
```
express Health Checks and Graceful Shutdown Health Checks and Graceful Shutdown
===================================
Graceful shutdown
-----------------
When you deploy a new version of your application, you must replace the previous version. The [process manager](pm) you’re using will first send a SIGTERM signal to the application to notify it that it will be killed. Once the application gets this signal, it should stop accepting new requests, finish all the ongoing requests, clean up the resources it used, including database connections and file locks then exit.
### Example Graceful Shutdown
```
const server = app.listen(port)
process.on('SIGTERM', () => {
debug('SIGTERM signal received: closing HTTP server')
server.close(() => {
debug('HTTP server closed')
})
})
```
Health checks
-------------
A load balancer uses health checks to determine if an application instance is healthy and can accept requests. For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/):
* `liveness`, that determines when to restart a container.
* `readiness`, that determines when a container is ready to start accepting traffic. When a pod is not ready, it is removed from the service load balancers.
Third-party solutions
---------------------
**Warning**: This information refers to third-party sites, products, or modules that are not maintained by the Expressjs team. Listing here does not constitute an endorsement or recommendation from the Expressjs project team.
### Terminus
[Terminus](https://github.com/godaddy/terminus) is an open-source project that adds health checks and graceful shutdown to your application to eliminate the need to write boilerplate code. You just provide the cleanup logic for graceful shutdowns and the health check logic for health checks, and terminus handles the rest.
Install terminus as follows:
```
$ npm i @godaddy/terminus --save
```
Here’s a basic template that illustrates using terminus. For more information, see <https://github.com/godaddy/terminus>.
```
const http = require('http')
const express = require('express')
const { createTerminus } = require('@godaddy/terminus')
const app = express()
app.get('/', (req, res) => {
res.send('ok')
})
const server = http.createServer(app)
function onSignal () {
console.log('server is starting cleanup')
// start cleanup of resource, like databases or file descriptors
}
async function onHealthCheck () {
// checks if the system is healthy, like the db connection is live
// resolves, if health, rejects if not
}
createTerminus(server, {
signal: 'SIGINT',
healthChecks: { '/healthcheck': onHealthCheck },
onSignal
})
server.listen(3000)
```
### Lightship
[Lightship](https://github.com/gajus/lightship) is an open-source project that adds health, readiness and liveness checks to your application. Lightship is a standalone HTTP-service that runs as a separate HTTP service; this allows having health-readiness-liveness HTTP endpoints without exposing them on the public interface.
Install Lightship as follows:
```
$ npm install lightship
```
Basic template that illustrates using Lightship:
```
const http = require('http')
const express = require('express')
const {
createLightship
} = require('lightship')
// Lightship will start a HTTP service on port 9000.
const lightship = createLightship()
const app = express()
app.get('/', (req, res) => {
res.send('ok')
})
app.listen(3000, () => {
lightship.signalReady()
})
// You can signal that the service is not ready using `lightship.signalNotReady()`.
```
[Lightship documentation](https://github.com/gajus/lightship) provides examples of the corresponding [Kubernetes configuration](https://github.com/gajus/lightship#lightship-usage-kubernetes-container-probe-configuration) and a complete example of integration with [Express.js](https://github.com/gajus/lightship#using-with-expressjs).
### http-terminator
[http-terminator](https://github.com/gajus/http-terminator) implements logic for gracefully terminating an express.js server.
Terminating a HTTP server in Node.js requires keeping track of all open connections and signaling them that the server is shutting down. http-terminator implements the logic for tracking all connections and their termination upon a timeout. http-terminator also ensures graceful communication of the server intention to shutdown to any clients that are currently receiving response from this server.
Install http-terminator as follows:
```
$ npm install http-terminator
```
Basic template that illustrates using http-terminator:
```
const express = require('express')
const { createHttpTerminator } = require('http-terminator')
const app = express()
const server = app.listen(3000)
const httpTerminator = createHttpTerminator({ server })
app.get('/', (req, res) => {
res.send('ok')
})
// A server will terminate after invoking `httpTerminator.terminate()`.
// Note: Timeout is used for illustration of delayed termination purposes only.
setTimeout(() => {
httpTerminator.terminate()
}, 1000)
```
[http-terminator documentation](https://github.com/gajus/http-terminator) provides API documentation and comparison to other existing third-party solutions.
### express-actuator
[express-actuator](https://github.com/rcruzper/express-actuator) is a middleware to add endpoints to help you monitor and manage applications.
Install express-actuator as follows:
```
$ npm install --save express-actuator
```
Basic template that illustrates using express-actuator:
```
const express = require('express')
const actuator = require('express-actuator')
const app = express()
app.use(actuator())
app.listen(3000)
```
The [express-actuator documentation](https://github.com/rcruzper/express-actuator) provides different options for customization.
express Production Best Practices: Security Production Best Practices: Security
===================================
Overview
--------
The term *“production”* refers to the stage in the software lifecycle when an application or API is generally available to its end-users or consumers. In contrast, in the *“development”* stage, you’re still actively writing and testing code, and the application is not open to external access. The corresponding system environments are known as *production* and *development* environments, respectively.
Development and production environments are usually set up differently and have vastly different requirements. What’s fine in development may not be acceptable in production. For example, in a development environment you may want verbose logging of errors for debugging, while the same behavior can become a security concern in a production environment. And in development, you don’t need to worry about scalability, reliability, and performance, while those concerns become critical in production.
**Note**: If you believe you have discovered a security vulnerability in Express, please see [Security Policies and Procedures](https://expressjs.com/en/resources/contributing.html#security-policies-and-procedures).
Security best practices for Express applications in production include:
* [Don’t use deprecated or vulnerable versions of Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
* [Use TLS](#use-tls)
* [Use Helmet](#use-helmet)
* [Use cookies securely](#use-cookies-securely)
* [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization)
* [Ensure your dependencies are secure](#ensure-your-dependencies-are-secure)
* [Avoid other known vulnerabilities](#avoid-other-known-vulnerabilities)
* [Additional considerations](#additional-considerations)
Don’t use deprecated or vulnerable versions of Express
------------------------------------------------------
Express 2.x and 3.x are no longer maintained. Security and performance issues in these versions won’t be fixed. Do not use them! If you haven’t moved to version 4, follow the [migration guide](../guide/migrating-4).
Also ensure you are not using any of the vulnerable Express versions listed on the [Security updates page](security-updates). If you are, update to one of the stable releases, preferably the latest.
Use TLS
-------
If your app deals with or transmits sensitive data, use [Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) to secure the connection and the data. This technology encrypts data before it is sent from the client to the server, thus preventing some common (and easy) hacks. Although Ajax and POST requests might not be visibly obvious and seem “hidden” in browsers, their network traffic is vulnerable to [packet sniffing](https://en.wikipedia.org/wiki/Packet_analyzer) and [man-in-the-middle attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).
You may be familiar with Secure Socket Layer (SSL) encryption. [TLS is simply the next progression of SSL](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515(v=vs.85).aspx). In other words, if you were using SSL before, consider upgrading to TLS. In general, we recommend Nginx to handle TLS. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations).
Also, a handy tool to get a free TLS certificate is [Let’s Encrypt](https://letsencrypt.org/about/), a free, automated, and open certificate authority (CA) provided by the [Internet Security Research Group (ISRG)](https://www.abetterinternet.org/).
Use Helmet
----------
[Helmet](https://helmetjs.github.io/) can help protect your app from some well-known web vulnerabilities by setting HTTP headers appropriately.
Helmet is a collection of several smaller middleware functions that set security-related HTTP response headers. Some examples include:
* `helmet.contentSecurityPolicy` which sets the `Content-Security-Policy` header. This helps prevent cross-site scripting attacks among many other things.
* `helmet.hsts` which sets the `Strict-Transport-Security` header. This helps enforce secure (HTTPS) connections to the server.
* `helmet.frameguard` which sets the `X-Frame-Options` header. This provides [clickjacking](https://www.owasp.org/index.php/Clickjacking) protection.
Helmet includes several other middleware functions which you can read about [at its documentation website](https://helmetjs.github.io/).
Install Helmet like any other module:
```
$ npm install --save helmet
```
Then to use it in your code:
```
// ...
const helmet = require('helmet')
app.use(helmet())
// ...
```
### Reduce Fingerprinting
It can help to provide an extra layer of obsecurity to reduce server fingerprinting. Though not a security issue itself, a method to improve the overall posture of a web server is to take measures to reduce the ability to fingerprint the software being used on the server. Server software can be fingerprinted by kwirks in how they respond to specific requests.
By default, Express.js sends the `X-Powered-By` response header banner. This can be disabled using the `app.disable()` method:
```
app.disable('x-powered-by')
```
**Note**: Disabling the `X-Powered-By header` does not prevent a sophisticated attacker from determining that an app is running Express. It may discourage a casual exploit, but there are other ways to determine an app is running Express.
Express.js also sends it’s own formatted 404 Not Found messages and own formatter error response messages. These can be changed by [adding your own not found handler](../starter/faq#how-do-i-handle-404-responses) and [writing your own error handler](../guide/error-handling#writing-error-handlers):
```
// last app.use calls right before app.listen():
// custom 404
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!")
})
// custom error handler
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
```
Use cookies securely
--------------------
To ensure cookies don’t open your app to exploits, don’t use the default session cookie name and set cookie security options appropriately.
There are two main middleware cookie session modules:
* [express-session](https://www.npmjs.com/package/express-session) that replaces `express.session` middleware built-in to Express 3.x.
* [cookie-session](https://www.npmjs.com/package/cookie-session) that replaces `express.cookieSession` middleware built-in to Express 3.x.
The main difference between these two modules is how they save cookie session data. The [express-session](https://www.npmjs.com/package/express-session) middleware stores session data on the server; it only saves the session ID in the cookie itself, not session data. By default, it uses in-memory storage and is not designed for a production environment. In production, you’ll need to set up a scalable session-store; see the list of [compatible session stores](https://github.com/expressjs/session#compatible-session-stores).
In contrast, [cookie-session](https://www.npmjs.com/package/cookie-session) middleware implements cookie-backed storage: it serializes the entire session to the cookie, rather than just a session key. Only use it when session data is relatively small and easily encoded as primitive values (rather than objects). Although browsers are supposed to support at least 4096 bytes per cookie, to ensure you don’t exceed the limit, don’t exceed a size of 4093 bytes per domain. Also, be aware that the cookie data will be visible to the client, so if there is any reason to keep it secure or obscure, then express-session may be a better choice.
### Don’t use the default session cookie name
Using the default session cookie name can open your app to attacks. The security issue posed is similar to `X-Powered-By`: a potential attacker can use it to fingerprint the server and target attacks accordingly.
To avoid this problem, use generic cookie names; for example using [express-session](https://www.npmjs.com/package/express-session) middleware:
```
const session = require('express-session')
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 's3Cur3',
name: 'sessionId'
}))
```
### Set cookie security options
Set the following cookie options to enhance security:
* `secure` - Ensures the browser only sends the cookie over HTTPS.
* `httpOnly` - Ensures the cookie is sent only over HTTP(S), not client JavaScript, helping to protect against cross-site scripting attacks.
* `domain` - indicates the domain of the cookie; use it to compare against the domain of the server in which the URL is being requested. If they match, then check the path attribute next.
* `path` - indicates the path of the cookie; use it to compare against the request path. If this and domain match, then send the cookie in the request.
* `expires` - use to set expiration date for persistent cookies.
Here is an example using [cookie-session](https://www.npmjs.com/package/cookie-session) middleware:
```
const session = require('cookie-session')
const express = require('express')
const app = express()
const expiryDate = new Date(Date.now() + 60 * 60 * 1000) // 1 hour
app.use(session({
name: 'session',
keys: ['key1', 'key2'],
cookie: {
secure: true,
httpOnly: true,
domain: 'example.com',
path: 'foo/bar',
expires: expiryDate
}
}))
```
Prevent brute-force attacks against authorization
-------------------------------------------------
Make sure login endpoints are protected to make private data more secure.
A simple and powerful technique is to block authorization attempts using two metrics:
1. The first is number of consecutive failed attempts by the same user name and IP address.
2. The second is number of failed attempts from an IP address over some long period of time. For example, block an IP address if it makes 100 failed attempts in one day.
[rate-limiter-flexible](https://github.com/animir/node-rate-limiter-flexible) package provides tools to make this technique easy and fast. You can find [an example of brute-force protection in the documentation](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#login-endpoint-protection)
Ensure your dependencies are secure
-----------------------------------
Using npm to manage your application’s dependencies is powerful and convenient. But the packages that you use may contain critical security vulnerabilities that could also affect your application. The security of your app is only as strong as the “weakest link” in your dependencies.
Since npm@6, npm automatically reviews every install request. Also you can use ‘npm audit’ to analyze your dependency tree.
```
$ npm audit
```
If you want to stay more secure, consider [Snyk](https://snyk.io/).
Snyk offers both a [command-line tool](https://www.npmjs.com/package/snyk) and a [Github integration](https://snyk.io/docs/github) that checks your application against [Snyk’s open source vulnerability database](https://snyk.io/vuln/) for any known vulnerabilities in your dependencies. Install the CLI as follows:
```
$ npm install -g snyk
$ cd your-app
```
Use this command to test your application for vulnerabilities:
```
$ snyk test
```
Use this command to open a wizard that walks you through the process of applying updates or patches to fix the vulnerabilities that were found:
```
$ snyk wizard
```
Avoid other known vulnerabilities
---------------------------------
Keep an eye out for [Node Security Project](https://npmjs.com/advisories) or [Snyk](https://snyk.io/vuln/) advisories that may affect Express or other modules that your app uses. In general, these databases are excellent resources for knowledge and tools about Node security.
Finally, Express apps - like any other web apps - can be vulnerable to a variety of web-based attacks. Familiarize yourself with known [web vulnerabilities](https://www.owasp.org/www-project-top-ten/) and take precautions to avoid them.
Additional considerations
-------------------------
Here are some further recommendations from the excellent [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). Refer to that blog post for all the details on these recommendations:
* Use [csurf](https://www.npmjs.com/package/csurf) middleware to protect against cross-site request forgery (CSRF).
* Always filter and sanitize user input to protect against cross-site scripting (XSS) and command injection attacks.
* Defend against SQL injection attacks by using parameterized queries or prepared statements.
* Use the open-source [sqlmap](http://sqlmap.org/) tool to detect SQL injection vulnerabilities in your app.
* Use the [nmap](https://nmap.org/) and [sslyze](https://github.com/nabla-c0d3/sslyze) tools to test the configuration of your SSL ciphers, keys, and renegotiation as well as the validity of your certificate.
* Use [safe-regex](https://www.npmjs.com/package/safe-regex) to ensure your regular expressions are not susceptible to [regular expression denial of service](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS) attacks.
| programming_docs |
express Process managers for Express apps Process managers for Express apps
=================================
**Warning**: This information refers to third-party sites, products, or modules that are not maintained by the Expressjs team. Listing here does not constitute an endorsement or recommendation from the Expressjs project team.
When you run Express apps for production, it is helpful to use a *process manager* to:
* Restart the app automatically if it crashes.
* Gain insights into runtime performance and resource consumption.
* Modify settings dynamically to improve performance.
* Control clustering.
A process manager is somewhat like an application server: it’s a “container” for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime.
The most popular process managers for Express and other Node.js applications are:
* **[Forever](https://github.com/foreverjs/forever)**: A simple command-line interface tool to ensure that a script runs continuously (forever). Forever’s simple interface makes it ideal for running smaller deployments of Node.js apps and scripts.
* **[PM2](https://github.com/Unitech/pm2)**: A production process manager for Node.js applications that has a built-in load balancer. PM2 enables you to keep applications alive forever, reloads them without downtime, helps you to manage application logging, monitoring, and clustering.
* **[StrongLoop Process Manager (Strong-PM)](http://strong-pm.io/)**: A production process manager for Node.js applications with built-in load balancing, monitoring, and multi-host deployment. Includes a CLI to build, package, and deploy Node.js applications to a local or remote system.
* **SystemD**: The default process manager on modern Linux distributions, that makes it simple to run a Node application as a service. For more information, see [“Run node.js service with systemd” by Ralph Slooten (@axllent)](https://www.axllent.org/docs/view/nodejs-service-with-systemd/).
express Security updates Security updates
================
Node.js vulnerabilities directly affect Express. Therefore [keep a watch on Node.js vulnerabilities](http://blog.nodejs.org/vulnerability/) and make sure you are using the latest stable version of Node.js.
The list below enumerates the Express vulnerabilities that were fixed in the specified version update.
**NOTE**: If you believe you have discovered a security vulnerability in Express, please see [Security Policies and Procedures](https://expressjs.com/en/resources/contributing.html#security-policies-and-procedures).
4.x
---
* 4.16.0
+ The dependency `forwarded` has been updated to address a [vulnerability](https://npmjs.com/advisories/527). This may affect your application if the following APIs are used: `req.host`, `req.hostname`, `req.ip`, `req.ips`, `req.protocol`.
+ The dependency `mime` has been updated to address a [vulnerability](https://npmjs.com/advisories/535), but this issue does not impact Express.
+ The dependency `send` has been updated to provide a protection against a [Node.js 8.5.0 vulnerability](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). This only impacts running Express on the specific Node.js version 8.5.0.
* 4.15.5
+ The dependency `debug` has been updated to address a [vulnerability](https://snyk.io/vuln/npm:debug:20170905), but this issue does not impact Express.
+ The dependency `fresh` has been updated to address a [vulnerability](https://npmjs.com/advisories/526). This will affect your application if the following APIs are used: `express.static`, `req.fresh`, `res.json`, `res.jsonp`, `res.send`, `res.sendfile` `res.sendFile`, `res.sendStatus`.
* 4.15.3
+ The dependency `ms` has been updated to address a [vulnerability](https://snyk.io/vuln/npm:ms:20170412). This may affect your application if untrusted string input is passed to the `maxAge` option in the following APIs: `express.static`, `res.sendfile`, and `res.sendFile`.
* 4.15.2
+ The dependency `qs` has been updated to address a [vulnerability](https://snyk.io/vuln/npm:qs:20170213), but this issue does not impact Express. Updating to 4.15.2 is a good practice, but not required to address the vulnerability.
* 4.11.1
+ Fixed root path disclosure vulnerability in `express.static`, `res.sendfile`, and `res.sendFile`
* 4.10.7
+ Fixed open redirect vulnerability in `express.static` ([advisory](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)).
* 4.8.8
+ Fixed directory traversal vulnerabilities in `express.static` ([advisory](http://npmjs.com/advisories/32) , [CVE-2014-6394](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6394)).
* 4.8.4
+ Node.js 0.10 can leak `fd`s in certain situations that affect `express.static` and `res.sendfile`. Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness.
* 4.8.0
+ Sparse arrays that have extremely high indexes in the query string could cause the process to run out of memory and crash the server.
+ Extremely nested query string objects could cause the process to block and make the server unresponsive temporarily.
3.x
---
**Express 3.x IS NO LONGER MAINTAINED**
Known and unknown security issues in 3.x have not been addressed since the last update (1 August, 2015). Using the 3.x line should not be considered secure.
* 3.19.1
+ Fixed root path disclosure vulnerability in `express.static`, `res.sendfile`, and `res.sendFile`
* 3.19.0
+ Fixed open redirect vulnerability in `express.static` ([advisory](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)).
* 3.16.10
+ Fixed directory traversal vulnerabilities in `express.static`.
* 3.16.6
+ Node.js 0.10 can leak `fd`s in certain situations that affect `express.static` and `res.sendfile`. Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness.
* 3.16.0
+ Sparse arrays that have extremely high indexes in query string could cause the process to run out of memory and crash the server.
+ Extremely nested query string objects could cause the process to block and make the server unresponsive temporarily.
* 3.3.0
+ The 404 response of an unsupported method override attempt was susceptible to cross-site scripting attacks.
express Production best practices: performance and reliability Production best practices: performance and reliability
======================================================
Overview
--------
This article discusses performance and reliability best practices for Express applications deployed to production.
This topic clearly falls into the “devops” world, spanning both traditional development and operations. Accordingly, the information is divided into two parts:
* Things to do in your code (the dev part):
+ [Use gzip compression](#use-gzip-compression)
+ [Don’t use synchronous functions](#dont-use-synchronous-functions)
+ [Do logging correctly](#do-logging-correctly)
+ [Handle exceptions properly](#handle-exceptions-properly)
* Things to do in your environment / setup (the ops part):
+ [Set NODE\_ENV to “production”](#set-node_env-to-production)
+ [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts)
+ [Run your app in a cluster](#run-your-app-in-a-cluster)
+ [Cache request results](#cache-request-results)
+ [Use a load balancer](#use-a-load-balancer)
+ [Use a reverse proxy](#use-a-reverse-proxy)
Things to do in your code
-------------------------
Here are some things you can do in your code to improve your application’s performance:
* [Use gzip compression](#use-gzip-compression)
* [Don’t use synchronous functions](#dont-use-synchronous-functions)
* [Do logging correctly](#do-logging-correctly)
* [Handle exceptions properly](#handle-exceptions-properly)
### Use gzip compression
Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the [compression](https://www.npmjs.com/package/compression) middleware for gzip compression in your Express app. For example:
```
const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())
```
For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx\_http\_gzip\_module](http://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation.
### Don’t use synchronous functions
Synchronous functions and methods tie up the executing process until they return. A single call to a synchronous function might return in a few microseconds or milliseconds, however in high-traffic websites, these calls add up and reduce the performance of the app. Avoid their use in production.
Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup.
If you are using Node.js 4.0+ or io.js 2.1.0+, you can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn’t want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#cli_trace_sync_io) for more information.
### Do logging correctly
In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html#console_console_1) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program.
#### For debugging
If you’re logging for purposes of debugging, then instead of using `console.log()`, use a special debugging module like [debug](https://www.npmjs.com/package/debug). This module enables you to use the DEBUG environment variable to control what debug messages are sent to `console.error()`, if any. To keep your app purely asynchronous, you’d still want to pipe `console.error()` to another program. But then, you’re not really going to debug in production, are you?
#### For app activity
If you’re logging app activity (for example, tracking traffic or API calls), instead of using `console.log()`, use a logging library like [Winston](https://www.npmjs.com/package/winston) or [Bunyan](https://www.npmjs.com/package/bunyan). For a detailed comparison of these two libraries, see the StrongLoop blog post [Comparing Winston and Bunyan Node.js Logging](https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/).
### Handle exceptions properly
Node apps crash when they encounter an uncaught exception. Not handling exceptions and taking appropriate actions will make your Express app crash and go offline. If you follow the advice in [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts) below, then your app will recover from a crash. Fortunately, Express apps typically have a short startup time. Nevertheless, you want to avoid crashing in the first place, and to do that, you need to handle exceptions properly.
To ensure you handle all exceptions, use the following techniques:
* [Use try-catch](#use-try-catch)
* [Use promises](#use-promises)
Before diving into these topics, you should have a basic understanding of Node/Express error handling: using error-first callbacks, and propagating errors in middleware. Node uses an “error-first callback” convention for returning errors from asynchronous functions, where the first parameter to the callback function is the error object, followed by result data in succeeding parameters. To indicate no error, pass null as the first parameter. The callback function must correspondingly follow the error-first callback convention to meaningfully handle the error. And in Express, the best practice is to use the next() function to propagate errors through the middleware chain.
For more on the fundamentals of error handling, see:
* [Error Handling in Node.js](https://www.joyent.com/developers/node/design/errors)
* [Building Robust Node Applications: Error Handling](https://strongloop.com/strongblog/robust-node-applications-error-handling/) (StrongLoop blog)
#### What not to do
One thing you should *not* do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable.
Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#process_event_uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error.
We also don’t recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn’t solve the problem and is a deprecated module.
#### Use try-catch
Try-catch is a JavaScript language construct that you can use to catch exceptions in synchronous code. Use try-catch, for example, to handle JSON parsing errors as shown below.
Use a tool such as [JSHint](http://jshint.com/) or [JSLint](http://www.jslint.com/) to help you find implicit exceptions like [reference errors on undefined variables](http://www.jshint.com/docs/options/#undef).
Here is an example of using try-catch to handle a potential process-crashing exception. This middleware function accepts a query field parameter named “params” that is a JSON object.
```
app.get('/search', (req, res) => {
// Simulating async operation
setImmediate(() => {
const jsonStr = req.query.params
try {
const jsonObj = JSON.parse(jsonStr)
res.send('Success')
} catch (e) {
res.status(400).send('Invalid JSON string')
}
})
})
```
However, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won’t catch a lot of exceptions.
#### Use promises
Promises will handle any exceptions (both explicit and implicit) in asynchronous code blocks that use `then()`. Just add `.catch(next)` to the end of promise chains. For example:
```
app.get('/', (req, res, next) => {
// do some sync stuff
queryDb()
.then((data) => makeCsv(data)) // handle data
.then((csv) => { /* handle csv */ })
.catch(next)
})
app.use((err, req, res, next) => {
// handle error
})
```
Now all errors asynchronous and synchronous get propagated to the error middleware.
However, there are two caveats:
1. All your asynchronous code must return promises (except emitters). If a particular library does not return promises, convert the base object by using a helper function like [Bluebird.promisifyAll()](http://bluebirdjs.com/docs/api/promise.promisifyall.html).
2. Event emitters (like streams) can still cause uncaught exceptions. So make sure you are handling the error event properly; for example:
```
const wrap = fn => (...args) => fn(...args).catch(args[2])
app.get('/', wrap(async (req, res, next) => {
const company = await getCompanyById(req.query.id)
const stream = getLogoStreamById(company.id)
stream.on('error', next).pipe(res)
}))
```
The `wrap()` function is a wrapper that catches rejected promises and calls `next()` with the error as the first argument. For details, see [Asynchronous Error Handling in Express with Promises, Generators and ES7](https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/#cleaner-code-with-generators).
For more information about error-handling by using promises, see [Promises in Node.js with Q – An Alternative to Callbacks](https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/).
Things to do in your environment / setup
----------------------------------------
Here are some things you can do in your system environment to improve your app’s performance:
* [Set NODE\_ENV to “production”](#set-node_env-to-production)
* [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts)
* [Run your app in a cluster](#run-your-app-in-a-cluster)
* [Cache request results](#cache-request-results)
* [Use a load balancer](#use-a-load-balancer)
* [Use a reverse proxy](#use-a-reverse-proxy)
### Set NODE\_ENV to “production”
The NODE\_ENV environment variable specifies the environment in which an application is running (usually, development or production). One of the simplest things you can do to improve performance is to set NODE\_ENV to “production.”
Setting NODE\_ENV to “production” makes Express:
* Cache view templates.
* Cache CSS files generated from CSS extensions.
* Generate less verbose error messages.
[Tests indicate](http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!
If you need to write environment-specific code, you can check the value of NODE\_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly.
In development, you typically set environment variables in your interactive shell, for example by using `export` or your `.bash_profile` file. But in general you shouldn’t do that on a production server; instead, use your OS’s init system (systemd or Upstart). The next section provides more details about using your init system in general, but setting NODE\_ENV is so important for performance (and easy to do), that it’s highlighted here.
With Upstart, use the `env` keyword in your job file. For example:
```
# /etc/init/env.conf
env NODE_ENV=production
```
For more information, see the [Upstart Intro, Cookbook and Best Practices](http://upstart.ubuntu.com/cookbook/#environment-variables).
With systemd, use the `Environment` directive in your unit file. For example:
```
# /etc/systemd/system/myservice.service
Environment=NODE_ENV=production
```
For more information, see [Using Environment Variables In systemd Units](https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html).
### Ensure your app automatically restarts
In production, you don’t want your application to be offline, ever. This means you need to make sure it restarts both if the app crashes and if the server itself crashes. Although you hope that neither of those events occurs, realistically you must account for both eventualities by:
* Using a process manager to restart the app (and Node) when it crashes.
* Using the init system provided by your OS to restart the process manager when the OS crashes. It’s also possible to use the init system without a process manager.
Node applications crash if they encounter an uncaught exception. The foremost thing you need to do is to ensure your app is well-tested and handles all exceptions (see [handle exceptions properly](#handle-exceptions-properly) for details). But as a fail-safe, put a mechanism in place to ensure that if and when your app crashes, it will automatically restart.
#### Use a process manager
In development, you started your app simply from the command line with `node server.js` or something similar. But doing this in production is a recipe for disaster. If the app crashes, it will be offline until you restart it. To ensure your app restarts if it crashes, use a process manager. A process manager is a “container” for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime.
In addition to restarting your app when it crashes, a process manager can enable you to:
* Gain insights into runtime performance and resource consumption.
* Modify settings dynamically to improve performance.
* Control clustering (StrongLoop PM and pm2).
The most popular process managers for Node are as follows:
* [StrongLoop Process Manager](http://strong-pm.io/)
* [PM2](https://github.com/Unitech/pm2)
* [Forever](https://www.npmjs.com/package/forever)
For a feature-by-feature comparison of the three process managers, see <http://strong-pm.io/compare/>. For a more detailed introduction to all three, see [Process managers for Express apps](pm).
Using any of these process managers will suffice to keep your application up, even if it does crash from time to time.
However, StrongLoop PM has lots of features that specifically target production deployment. You can use it and the related StrongLoop tools to:
* Build and package your app locally, then deploy it securely to your production system.
* Automatically restart your app if it crashes for any reason.
* Manage your clusters remotely.
* View CPU profiles and heap snapshots to optimize performance and diagnose memory leaks.
* View performance metrics for your application.
* Easily scale to multiple hosts with integrated control for Nginx load balancer.
As explained below, when you install StrongLoop PM as an operating system service using your init system, it will automatically restart when the system restarts. Thus, it will keep your application processes and clusters alive forever.
#### Use an init system
The next layer of reliability is to ensure that your app restarts when the server restarts. Systems can still go down for a variety of reasons. To ensure that your app restarts if the server crashes, use the init system built into your OS. The two main init systems in use today are [systemd](https://wiki.debian.org/systemd) and [Upstart](http://upstart.ubuntu.com/).
There are two ways to use init systems with your Express app:
* Run your app in a process manager, and install the process manager as a service with the init system. The process manager will restart your app when the app crashes, and the init system will restart the process manager when the OS restarts. This is the recommended approach.
* Run your app (and Node) directly with the init system. This is somewhat simpler, but you don’t get the additional advantages of using a process manager.
##### Systemd
Systemd is a Linux system and service manager. Most major Linux distributions have adopted systemd as their default init system.
A systemd service configuration file is called a *unit file*, with a filename ending in `.service`. Here’s an example unit file to manage a Node app directly. Replace the values enclosed in `<angle brackets>` for your system and app:
```
[Unit]
Description=<Awesome Express App>
[Service]
Type=simple
ExecStart=/usr/local/bin/node </projects/myapp/index.js>
WorkingDirectory=</projects/myapp>
User=nobody
Group=nogroup
# Environment variables:
Environment=NODE_ENV=production
# Allow many incoming connections
LimitNOFILE=infinity
# Allow core dumps for debugging
LimitCORE=infinity
StandardInput=null
StandardOutput=syslog
StandardError=syslog
Restart=always
[Install]
WantedBy=multi-user.target
```
For more information on systemd, see the [systemd reference (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html).
##### StrongLoop PM as a systemd service
You can easily install StrongLoop Process Manager as a systemd service. After you do, when the server restarts, it will automatically restart StrongLoop PM, which will then restart all the apps it is managing.
To install StrongLoop PM as a systemd service:
```
$ sudo sl-pm-install --systemd
```
Then start the service with:
```
$ sudo /usr/bin/systemctl start strong-pm
```
For more information, see [Setting up a production host (StrongLoop documentation)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHEL7+,Ubuntu15.04or15.10).
##### Upstart
Upstart is a system tool available on many Linux distributions for starting tasks and services during system startup, stopping them during shutdown, and supervising them. You can configure your Express app or process manager as a service and then Upstart will automatically restart it when it crashes.
An Upstart service is defined in a job configuration file (also called a “job”) with filename ending in `.conf`. The following example shows how to create a job called “myapp” for an app named “myapp” with the main file located at `/projects/myapp/index.js`.
Create a file named `myapp.conf` at `/etc/init/` with the following content (replace the bold text with values for your system and app):
```
# When to start the process
start on runlevel [2345]
# When to stop the process
stop on runlevel [016]
# Increase file descriptor limit to be able to handle more requests
limit nofile 50000 50000
# Use production mode
env NODE_ENV=production
# Run as www-data
setuid www-data
setgid www-data
# Run from inside the app dir
chdir /projects/myapp
# The process to start
exec /usr/local/bin/node /projects/myapp/index.js
# Restart the process if it is down
respawn
# Limit restart attempt to 10 times within 10 seconds
respawn limit 10 10
```
NOTE: This script requires Upstart 1.4 or newer, supported on Ubuntu 12.04-14.10.
Since the job is configured to run when the system starts, your app will be started along with the operating system, and automatically restarted if the app crashes or the system goes down.
Apart from automatically restarting the app, Upstart enables you to use these commands:
* `start myapp` – Start the app
* `restart myapp` – Restart the app
* `stop myapp` – Stop the app.
For more information on Upstart, see [Upstart Intro, Cookbook and Best Practises](http://upstart.ubuntu.com/cookbook).
##### StrongLoop PM as an Upstart service
You can easily install StrongLoop Process Manager as an Upstart service. After you do, when the server restarts, it will automatically restart StrongLoop PM, which will then restart all the apps it is managing.
To install StrongLoop PM as an Upstart 1.4 service:
```
$ sudo sl-pm-install
```
Then run the service with:
```
$ sudo /sbin/initctl start strong-pm
```
NOTE: On systems that don’t support Upstart 1.4, the commands are slightly different. See [Setting up a production host (StrongLoop documentation)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHELLinux5and6,Ubuntu10.04-.10,11.04-.10) for more information.
### Run your app in a cluster
In a multi-core system, you can increase the performance of a Node app by many times by launching a cluster of processes. A cluster runs multiple instances of the app, ideally one instance on each CPU core, thereby distributing the load and tasks among the instances.
IMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](http://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers.
In clustered apps, worker processes can crash individually without affecting the rest of the processes. Apart from performance advantages, failure isolation is another reason to run a cluster of app processes. Whenever a worker process crashes, always make sure to log the event and spawn a new process using cluster.fork().
#### Using Node’s cluster module
Clustering is made possible with Node’s [cluster module](https://nodejs.org/dist/latest-v4.x/docs/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers. However, rather than using this module directly, it’s far better to use one of the many tools out there that does it for you automatically; for example [node-pm](https://www.npmjs.com/package/node-pm) or [cluster-service](https://www.npmjs.com/package/cluster-service).
#### Using StrongLoop PM
If you deploy your application to StrongLoop Process Manager (PM), then you can take advantage of clustering *without* modifying your application code.
When StrongLoop Process Manager (PM) runs an application, it automatically runs it in a cluster with a number of workers equal to the number of CPU cores on the system. You can manually change the number of worker processes in the cluster using the slc command line tool without stopping the app.
For example, assuming you’ve deployed your app to prod.foo.com and StrongLoop PM is listening on port 8701 (the default), then to set the cluster size to eight using slc:
```
$ slc ctl -C http://prod.foo.com:8701 set-size my-app 8
```
For more information on clustering with StrongLoop PM, see [Clustering](https://docs.strongloop.com/display/SLC/Clustering) in StrongLoop documentation.
#### Using PM2
If you deploy your application with PM2, then you can take advantage of clustering *without* modifying your application code. You should ensure your [application is stateless](http://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) first, meaning no local data is stored in the process (such as sessions, websocket connections and the like).
When running an application with PM2, you can enable **cluster mode** to run it in a cluster with a number of instances of your choosing, such as the matching the number of available CPUs on the machine. You can manually change the number of processes in the cluster using the `pm2` command line tool without stopping the app.
To enable cluster mode, start your application like so:
```
# Start 4 worker processes
$ pm2 start npm --name my-app -i 4 -- start
# Auto-detect number of available CPUs and start that many worker processes
$ pm2 start npm --name my-app -i max -- start
```
This can also be configured within a PM2 process file (`ecosystem.config.js` or similar) by setting `exec_mode` to `cluster` and `instances` to the number of workers to start.
Once running, the application can be scaled like so:
```
# Add 3 more workers
$ pm2 scale my-app +3
# Scale to a specific number of workers
$ pm2 scale my-app 2
```
For more information on clustering with PM2, see [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in the PM2 documentation.
### Cache request results
Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly.
Use a caching server like [Varnish](https://www.varnish-cache.org/) or [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/) (see also [Nginx Caching](https://serversforhackers.com/nginx-caching/)) to greatly improve the speed and performance of your app.
### Use a load balancer
No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app’s performance and speed, and enable it to scale more than is possible with a single instance.
A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](http://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).
With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as *session affinity*, or *sticky sessions*, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/using-multiple-nodes).
### Use a reverse proxy
A reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things.
Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://www.nginx.com/) or [HAProxy](http://www.haproxy.org/) in production.
| programming_docs |
express Developing template engines for Express Developing template engines for Express
=======================================
Use the `app.engine(ext, callback)` method to create your own template engine. `ext` refers to the file extension, and `callback` is the template engine function, which accepts the following items as parameters: the location of the file, the options object, and the callback function.
The following code is an example of implementing a very simple template engine for rendering `.ntl` files.
```
const fs = require('fs') // this engine requires the fs module
app.engine('ntl', (filePath, options, callback) => { // define the template engine
fs.readFile(filePath, (err, content) => {
if (err) return callback(err)
// this is an extremely simple template engine
const rendered = content.toString()
.replace('#title#', `<title>${options.title}</title>`)
.replace('#message#', `<h1>${options.message}</h1>`)
return callback(null, rendered)
})
})
app.set('views', './views') // specify the views directory
app.set('view engine', 'ntl') // register the template engine
```
Your app will now be able to render `.ntl` files. Create a file named `index.ntl` in the `views` directory with the following content.
```
#title#
#message#
```
Then, create the following route in your app.
```
app.get('/', (req, res) => {
res.render('index', { title: 'Hey', message: 'Hello there!' })
})
```
When you make a request to the home page, `index.ntl` will be rendered as HTML.
express Basic routing Basic routing
=============
*Routing* refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
Each route can have one or more handler functions, which are executed when the route is matched.
Route definition takes the following structure:
```
app.METHOD(PATH, HANDLER)
```
Where:
* `app` is an instance of `express`.
* `METHOD` is an [HTTP request method](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods), in lowercase.
* `PATH` is a path on the server.
* `HANDLER` is the function executed when the route is matched.
This tutorial assumes that an instance of `express` named `app` is created and the server is running. If you are not familiar with creating an app and starting it, see the [Hello world example](hello-world).
The following examples illustrate defining simple routes.
Respond with `Hello World!` on the homepage:
```
app.get('/', (req, res) => {
res.send('Hello World!')
})
```
Respond to POST request on the root route (`/`), the application’s home page:
```
app.post('/', (req, res) => {
res.send('Got a POST request')
})
```
Respond to a PUT request to the `/user` route:
```
app.put('/user', (req, res) => {
res.send('Got a PUT request at /user')
})
```
Respond to a DELETE request to the `/user` route:
```
app.delete('/user', (req, res) => {
res.send('Got a DELETE request at /user')
})
```
For more details about routing, see the [routing guide](../guide/routing).
###
[Previous: Express application generator](generator) [Next: Serving static files in Express](static-files)
express Express examples Express examples
================
This page contains list of examples using Express.
* [auth](https://github.com/expressjs/express/tree/master/examples/auth) - Authentication with login and password
* [content-negotiation](https://github.com/expressjs/express/tree/master/examples/content-negotiation) - HTTP content negotiation
* [cookie-sessions](https://github.com/expressjs/express/tree/master/examples/cookie-sessions) - Working with cookie-based sessions
* [cookies](https://github.com/expressjs/express/tree/master/examples/cookies) - Working with cookies
* [downloads](https://github.com/expressjs/express/tree/master/examples/downloads) - Transferring files to client
* [ejs](https://github.com/expressjs/express/tree/master/examples/ejs) - Working with Embedded JavaScript templating (ejs)
* [error-pages](https://github.com/expressjs/express/tree/master/examples/error-pages) - Creating error pages
* [error](https://github.com/expressjs/express/tree/master/examples/error) - Working with error middleware
* [hello-world](https://github.com/expressjs/express/tree/master/examples/hello-world) - Simple request handler
* [markdown](https://github.com/expressjs/express/tree/master/examples/markdown) - Markdown as template engine
* [multi-router](https://github.com/expressjs/express/tree/master/examples/multi-router) - Working with multiple Express routers
* [multipart](https://github.com/expressjs/express/tree/master/examples/multipart) - Accepting multipart-encoded forms
* [mvc](https://github.com/expressjs/express/tree/master/examples/mvc) - MVC-style controllers
* [online](https://github.com/expressjs/express/tree/master/examples/online) - Tracking online user activity with `online` and `redis` packages
* [params](https://github.com/expressjs/express/tree/master/examples/params) - Working with route parameters
* [resource](https://github.com/expressjs/express/tree/master/examples/resource) - Multiple HTTP operations on the same resource
* [route-map](https://github.com/expressjs/express/tree/master/examples/route-map) - Organizing routes using a map
* [route-middleware](https://github.com/expressjs/express/tree/master/examples/route-middleware) - Working with route middleware
* [route-separation](https://github.com/expressjs/express/tree/master/examples/route-separation) - Organizing routes per each resource
* [search](https://github.com/expressjs/express/tree/master/examples/search) - Search API
* [session](https://github.com/expressjs/express/tree/master/examples/session) - User sessions
* [static-files](https://github.com/expressjs/express/tree/master/examples/static-files) - Serving static files
* [vhost](https://github.com/expressjs/express/tree/master/examples/vhost) - Working with virtual hosts
* [view-constructor](https://github.com/expressjs/express/tree/master/examples/view-constructor) - Rendering views dynamically
* [view-locals](https://github.com/expressjs/express/tree/master/examples/view-locals) - Saving data in request object between middleware calls
* [web-service](https://github.com/expressjs/express/tree/master/examples/web-service) - Simple API service
Additional examples
-------------------
These are some additional examples with more extensive integrations.
**Warning**: This information refers to third-party sites, products, or modules that are not maintained by the Expressjs team. Listing here does not constitute an endorsement or recommendation from the Expressjs project team.
* [prisma-express-graphql](https://github.com/prisma/prisma-examples/tree/latest/typescript/graphql-express) - GraphQL API with `express-graphql` using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
* [prisma-fullstack](https://github.com/prisma/prisma-examples/tree/latest/typescript/rest-nextjs-express) - Fullstack app with Next.js using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
* [prisma-rest-api-js](https://github.com/prisma/prisma-examples/tree/latest/javascript/rest-express) - REST API with Express in JavaScript using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
* [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/typescript/rest-express) - REST API with Express in TypeScript using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
###
[Previous: Static Files](static-files) [Next: FAQ](faq)
express Hello world example Hello world example
===================
Embedded below is essentially the simplest Express app you can create. It is a single file app — *not* what you’d get if you use the [Express generator](generator), which creates the scaffolding for a full app with numerous JavaScript files, Jade templates, and sub-directories for various purposes.
```
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
```
This app starts a server and listens on port 3000 for connections. The app responds with “Hello World!” for requests to the root URL (`/`) or *route*. For every other path, it will respond with a **404 Not Found**.
The example above is actually a working server: Go ahead and click on the URL shown. You’ll get a response, with real-time logs on the page, and any changes you make will be reflected in real time. This is powered by [RunKit](https://runkit.com), which provides an interactive JavaScript playground connected to a complete Node environment that runs in your web browser. Below are instructions for running the same app on your local machine.
RunKit is a third-party service not affiliated with the Express project.
### Running Locally
First create a directory named `myapp`, change to it and run `npm init`. Then install `express` as a dependency, as per the [installation guide](installing).
In the `myapp` directory, create a file named `app.js` and copy in the code from the example above.
The `req` (request) and `res` (response) are the exact same objects that Node provides, so you can invoke `req.pipe()`, `req.on('data', callback)`, and anything else you would do without Express involved.
Run the app with the following command:
```
$ node app.js
```
Then, load `http://localhost:3000/` in a browser to see the output.
###
[Previous: Installing](installing) [Next: Express Generator](generator)
express Serving static files in Express Serving static files in Express
===============================
To serve static files such as images, CSS files, and JavaScript files, use the `express.static` built-in middleware function in Express.
The function signature is:
```
express.static(root, [options])
```
The `root` argument specifies the root directory from which to serve static assets. For more information on the `options` argument, see [express.static](../index#express.static).
For example, use the following code to serve images, CSS files, and JavaScript files in a directory named `public`:
```
app.use(express.static('public'))
```
Now, you can load the files that are in the `public` directory:
```
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
```
Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL. To use multiple static assets directories, call the `express.static` middleware function multiple times:
```
app.use(express.static('public'))
app.use(express.static('files'))
```
Express looks up the files in the order in which you set the static directories with the `express.static` middleware function.
NOTE: For best results, [use a reverse proxy](../advanced/best-practice-performance#use-a-reverse-proxy) cache to improve performance of serving static assets.
To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](../index#app.use) for the static directory, as shown below:
```
app.use('/static', express.static('public'))
```
Now, you can load the files that are in the `public` directory from the `/static` path prefix.
```
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
```
However, the path that you provide to the `express.static` function is relative to the directory from where you launch your `node` process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:
```
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))
```
For more details about the `serve-static` function and its options, see [serve-static](https://expressjs.com/resources/middleware/serve-static.html).
###
[Previous: Basic Routing](basic-routing) [Next: More examples](examples)
express FAQ FAQ
===
How should I structure my application?
--------------------------------------
There is no definitive answer to this question. The answer depends on the scale of your application and the team that is involved. To be as flexible as possible, Express makes no assumptions in terms of structure.
Routes and other application-specific logic can live in as many files as you wish, in any directory structure you prefer. View the following examples for inspiration:
* [Route listings](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-L47)
* [Route map](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66)
* [MVC style controllers](https://github.com/expressjs/express/tree/master/examples/mvc)
Also, there are third-party extensions for Express, which simplify some of these patterns:
* [Resourceful routing](https://github.com/expressjs/express-resource)
How do I define models?
-----------------------
Express has no notion of a database. This concept is left up to third-party Node modules, allowing you to interface with nearly any database.
See [LoopBack](http://loopback.io) for an Express-based framework that is centered around models.
How can I authenticate users?
-----------------------------
Authentication is another opinionated area that Express does not venture into. You may use any authentication scheme you wish. For a simple username / password scheme, see [this example](https://github.com/expressjs/express/tree/master/examples/auth).
Which template engines does Express support?
--------------------------------------------
Express supports any template engine that conforms with the `(path, locals, callback)` signature. To normalize template engine interfaces and caching, see the [consolidate.js](https://github.com/visionmedia/consolidate.js) project for support. Unlisted template engines might still support the Express signature.
For more information, see [Using template engines with Express](../guide/using-template-engines).
How do I handle 404 responses?
------------------------------
In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. This behavior is because a 404 response simply indicates the absence of additional work to do; in other words, Express has executed all middleware functions and routes, and found that none of them responded. All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response:
```
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!")
})
```
Add routes dynamically at runtime on an instance of `express.Router()` so the routes are not superseded by a middleware function.
How do I setup an error handler?
--------------------------------
You define error-handling middleware in the same way as other middleware, except with four arguments instead of three; specifically with the signature `(err, req, res, next)`:
```
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
```
For more information, see [Error handling](../guide/error-handling).
How do I render plain HTML?
---------------------------
You don’t! There’s no need to “render” HTML with the `res.render()` function. If you have a specific file, use the `res.sendFile()` function. If you are serving many assets from a directory, use the `express.static()` middleware function.
### [Previous: More examples](examples)
express Installing Installing
==========
Assuming you’ve already installed [Node.js](https://nodejs.org/), create a directory to hold your application, and make that your working directory.
```
$ mkdir myapp
$ cd myapp
```
Use the `npm init` command to create a `package.json` file for your application. For more information on how `package.json` works, see [Specifics of npm’s package.json handling](https://docs.npmjs.com/files/package.json).
```
$ npm init
```
This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:
```
entry point: (index.js)
```
Enter `app.js`, or whatever you want the name of the main file to be. If you want it to be `index.js`, hit RETURN to accept the suggested default file name.
Now install Express in the `myapp` directory and save it in the dependencies list. For example:
```
$ npm install express
```
To install Express temporarily and not add it to the dependencies list:
```
$ npm install express --no-save
```
By default with version npm 5.0+ npm install adds the module to the `dependencies` list in the `package.json` file; with earlier versions of npm, you must specify the `--save` option explicitly. Then, afterwards, running `npm install` in the app directory will automatically install modules in the dependencies list.
### [Next: Hello World](hello-world)
express Express application generator Express application generator
=============================
Use the application generator tool, `express-generator`, to quickly create an application skeleton.
You can run the application generator with the `npx` command (available in Node.js 8.2.0).
```
$ npx express-generator
```
For earlier Node versions, install the application generator as a global npm package and then launch it:
```
$ npm install -g express-generator
$ express
```
Display the command options with the `-h` option:
```
$ express -h
Usage: express [options] [dir]
Options:
-h, --help output usage information
--version output the version number
-e, --ejs add ejs engine support
--hbs add handlebars engine support
--pug add pug engine support
-H, --hogan add hogan.js engine support
--no-view generate without view engine
-v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
--git add .gitignore
-f, --force force on non-empty directory
```
For example, the following creates an Express app named *myapp*. The app will be created in a folder named *myapp* in the current working directory and the view engine will be set to [Pug](https://pugjs.org/ "Pug documentation"):
```
$ express --view=pug myapp
create : myapp
create : myapp/package.json
create : myapp/app.js
create : myapp/public
create : myapp/public/javascripts
create : myapp/public/images
create : myapp/routes
create : myapp/routes/index.js
create : myapp/routes/users.js
create : myapp/public/stylesheets
create : myapp/public/stylesheets/style.css
create : myapp/views
create : myapp/views/index.pug
create : myapp/views/layout.pug
create : myapp/views/error.pug
create : myapp/bin
create : myapp/bin/www
```
Then install dependencies:
```
$ cd myapp
$ npm install
```
On MacOS or Linux, run the app with this command:
```
$ DEBUG=myapp:* npm start
```
On Windows Command Prompt, use this command:
```
> set DEBUG=myapp:* & npm start
```
On Windows PowerShell, use this command:
```
PS> $env:DEBUG='myapp:*'; npm start
```
Then load `http://localhost:3000/` in your browser to access the app.
The generated app has the following directory structure:
```
.
├── app.js
├── bin
│ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
└── views
├── error.pug
├── index.pug
└── layout.pug
7 directories, 9 files
```
The app structure created by the generator is just one of many ways to structure Express apps. Feel free to use this structure or modify it to best suit your needs.
###
[Previous: Hello World](hello-world) [Next: Basic routing](basic-routing)
| programming_docs |
i3 i3 User’s Guide i3 User’s Guide
===============
Michael Stapelberg
<[[email protected]](mailto:[email protected])>
Table of Contents **JavaScript must be enabled in your browser to display the table of contents.**
This document contains all the information you need to configure and use the i3 window manager. If it does not you can [contact us](https://i3wm.org/contact/) on [GitHub Discussions](https://github.com/i3/i3/discussions), IRC, or the mailing list.
1. Default keybindings
----------------------
For the "too long; didn’t read" people, here is an overview of the default keybindings (click to see the full-size image):
**Keys to use with $mod (Alt):**
**Keys to use with Shift+$mod:**
The red keys are the modifiers you need to press (by default), the blue keys are your homerow.
Note that when starting i3 without a config file, i3-config-wizard will offer you to create a config file in which the key positions (!) match what you see in the image above, regardless of the keyboard layout you are using. If you prefer to use a config file where the key letters match what you are seeing above, just decline i3-config-wizard’s offer and base your config on /etc/i3/config.
2. Using i3
-----------
Throughout this guide, the keyword $mod will be used to refer to the configured modifier. This is the Alt key (Mod1) by default, with the Windows key (Mod4) being a popular alternative that largely prevents conflicts with application-defined shortcuts.
### 2.1. Opening terminals and moving around
One very basic operation is opening a new terminal. By default, the keybinding for this is $mod+Enter, that is Alt+Enter (Mod1+Enter) in the default configuration. By pressing $mod+Enter, a new terminal will be opened. It will fill the whole space available on your screen.
If you now open another terminal, i3 will place it next to the current one, splitting the screen size in half. Depending on your monitor, i3 will put the created window beside the existing window (on wide displays) or below the existing window (rotated displays).
To move the focus between the two terminals, you can use the arrow keys. For convenience, the arrows are also available directly on the [keyboard’s home row](https://en.wikipedia.org/wiki/Touch_typing) underneath your right hand:
| $mod+j | left |
| $mod+k | down |
| $mod+l | up |
| $mod+; | right |
Note that this differs by one key from the popular text editor vi, which was [developed on an ADM-3A terminal and therefore uses hjkl instead of jkl;](https://twitter.com/hillelogram/status/1326600125569961991) — i3’s default is meant to require minimal finger movement, but some vi users change their i3 config for consistency.
At the moment, your workspace is split (it contains two terminals) in a specific direction (horizontal by default). Every window can be split horizontally or vertically again, just like the workspace. The terminology is "window" for a container that actually contains an X11 window (like a terminal or browser) and "split container" for containers that consist of one or more windows.
To split a window vertically, press $mod+v before you create the new window. To split it horizontally, press $mod+h.
### 2.2. Changing the container layout
A split container can have one of the following layouts:
splith/splitv Windows are sized so that every window gets an equal amount of space in the container. splith distributes the windows horizontally (windows are right next to each other), splitv distributes them vertically (windows are on top of each other).
stacking Only the focused window in the container is displayed. You get a list of windows at the top of the container.
tabbed The same principle as stacking, but the list of windows at the top is only a single line which is vertically split.
To switch modes, press $mod+e for splith/splitv (it toggles), $mod+s for stacking and $mod+w for tabbed.
### 2.3. Toggling fullscreen mode for a window
To display a window in fullscreen mode or to go out of fullscreen mode again, press $mod+f.
There is also a global fullscreen mode in i3 in which the client will span all available outputs (the command is fullscreen toggle global).
### 2.4. Opening other applications
Aside from opening applications from a terminal, you can also use the handy dmenu which is opened by pressing $mod+d by default. Just type the name (or a part of it) of the application which you want to open. The corresponding application has to be in your $PATH for this to work.
Additionally, if you have applications you open very frequently, you can create a keybinding for starting the application directly. See the section [[configuring]](#configuring) for details.
### 2.5. Closing windows
If an application does not provide a mechanism for closing (most applications provide a menu, the escape key or a shortcut like Control+w to close), you can press $mod+Shift+q to kill a window. For applications which support the WM\_DELETE protocol, this will correctly close the application (saving any modifications or doing other cleanup). If the application doesn’t support the WM\_DELETE protocol your X server will kill the window and the behaviour depends on the application.
### 2.6. Using workspaces
Workspaces are an easy way to group a set of windows. By default, you are on the first workspace, as the bar on the bottom left indicates. To switch to another workspace, press $mod+num where num is the number of the workspace you want to use. If the workspace does not exist yet, it will be created.
A common paradigm is to put the web browser on one workspace, communication applications (mutt, irssi, …) on another one, and the ones with which you work, on the third one. Of course, there is no need to follow this approach.
If you have multiple screens, a workspace will be created on each screen at startup. If you open a new workspace, it will be bound to the screen you created it on. When you switch to a workspace on another screen, i3 will set focus to that screen.
### 2.7. Moving windows to workspaces
To move a window to another workspace, simply press $mod+Shift+num where num is (like when switching workspaces) the number of the target workspace. Similarly to switching workspaces, the target workspace will be created if it does not yet exist.
### 2.8. Resizing
The easiest way to resize a container is by using the mouse: Grab the border and move it to the wanted size.
You can also use [[binding\_modes]](#binding_modes) to define a mode for resizing via the keyboard. To see an example for this, look at the [default config](https://github.com/i3/i3/blob/next/etc/config.keycodes) provided by i3.
### 2.9. Restarting i3 inplace
To restart i3 in place (and thus get into a clean state if there is a bug, or to upgrade to a newer version of i3) you can use $mod+Shift+r.
### 2.10. Exiting i3
To cleanly exit i3 without killing your X server, you can use $mod+Shift+e. By default, a dialog will ask you to confirm if you really want to quit.
### 2.11. Floating
Floating mode is the opposite of tiling mode. The position and size of a window are not managed automatically by i3, but manually by you. Using this mode violates the tiling paradigm but can be useful for some corner cases like "Save as" dialog windows, or toolbar windows (GIMP or similar). Those windows usually set the appropriate hint and are opened in floating mode by default.
You can toggle floating mode for a window by pressing $mod+Shift+Space. By dragging the window’s titlebar with your mouse you can move the window around. By grabbing the borders and moving them you can resize the window. You can also do that by using the [[floating\_modifier]](#floating_modifier). Another way to resize floating windows using the mouse is to right-click on the titlebar and drag.
For resizing floating windows with your keyboard, see the resizing binding mode provided by the i3 [default config](https://github.com/i3/i3/blob/next/etc/config.keycodes).
Floating windows are always on top of tiling windows.
### 2.12. Moving tiling containers with the mouse
Since i3 4.21, it’s possible to drag tiling containers using the mouse. The drag can be initiated either by dragging the window’s titlebar or by pressing the [[floating\_modifier]](#floating_modifier) and dragging the container while holding the left-click button.
Once the drag is initiated and the cursor has left the original container, drop indicators are created according to the position of the cursor relatively to the target container. These indicators help you understand what the resulting [[tree]](#tree) layout is going to be after you release the mouse button.
The possible drop positions are:
Drop on container This happens when the mouse is relatively near the center of a container. If the mouse is released, the result is exactly as if you had run the move container to mark command. See [[move\_to\_mark]](#move_to_mark).
Drop as sibling This happens when the mouse is relatively near the edge of a container. If the mouse is released, the dragged container will become a sibling of the target container, placed left/right/up/down according to the position of the indicator. This might or might not create a new v-split or h-split according to the previous layout of the target container. For example, if the target container is in an h-split and you drop the dragged container below it, the new layout will have to be a v-split.
Drop to parent This happens when the mouse is relatively near the edge of a container (but even closer to the border in comparison to the sibling case above) **and** if that edge is also the parent container’s edge. For example, if three containers are in a horizontal layout then edges where this can happen is the left edge of the left container, the right edge of the right container and all bottom and top edges of all three containers. If the mouse is released, the container is first dropped as a sibling to the target container, like in the case above, and then is moved directionally like with the move left|right|down|up command. See [[move\_direction]](#move_direction).
The color of the indicator matches the client.focused setting. See [[client\_colors]](#client_colors).
3. Tree
-------
i3 stores all information about the X11 outputs, workspaces and layout of the windows on them in a tree. The root node is the X11 root window, followed by the X11 outputs, then dock areas and a content container, then workspaces and finally the windows themselves. In previous versions of i3 we had multiple lists (of outputs, workspaces) and a table for each workspace. That approach turned out to be complicated to use (snapping), understand and implement.
### 3.1. The tree consists of Containers
The building blocks of our tree are so-called Containers. A Container can host a window (meaning an X11 window, one that you can actually see and use, like a browser). Alternatively, it could contain one or more Containers. A simple example is the workspace: When you start i3 with a single monitor, a single workspace and you open two terminal windows, you will end up with a tree like this:
Figure 1. Two terminals on standard workspace ### 3.2. Orientation and Split Containers
It is only natural to use so-called Split Containers in order to build a layout when using a tree as data structure. In i3, every Container has an orientation (horizontal, vertical or unspecified) and the orientation depends on the layout the container is in (vertical for splitv and stacking, horizontal for splith and tabbed). So, in our example with the workspace, the default layout of the workspace Container is splith (most monitors are widescreen nowadays). If you change the layout to splitv ($mod+v in the default config) and **then** open two terminals, i3 will configure your windows like this:
Figure 2. Vertical Workspace Orientation An interesting new feature of i3 since version 4 is the ability to split anything: Let’s assume you have two terminals on a workspace (with splith layout, that is horizontal orientation), focus is on the right terminal. Now you want to open another terminal window below the current one. If you would just open a new terminal window, it would show up to the right due to the splith layout. Instead, press $mod+v to split the container with the splitv layout (to open a Horizontal Split Container, use $mod+h). Now you can open a new terminal and it will open below the current one:
Figure 3. Vertical Split Container You probably guessed it already: There is no limit on how deep your hierarchy of splits can be.
### 3.3. Focus parent
Let’s stay with our example from above. We have a terminal on the left and two vertically split terminals on the right, focus is on the bottom right one. When you open a new terminal, it will open below the current one.
So, how can you open a new terminal window to the **right** of the current one? The solution is to use focus parent, which will focus the Parent Container of the current Container. In default configuration, use $mod+a to navigate one Container up the tree (you can repeat this multiple times until you get to the Workspace Container). In this case, you would focus the Vertical Split Container which is **inside** the horizontally oriented workspace. Thus, now new windows will be opened to the right of the Vertical Split Container:
Figure 4. Focus parent, then open new terminal ### 3.4. Implicit containers
In some cases, i3 needs to implicitly create a container to fulfill your command.
One example is the following scenario: You start i3 with a single monitor and a single workspace on which you open three terminal windows. All these terminal windows are directly attached to one node inside i3’s layout tree, the workspace node. By default, the workspace node’s orientation is horizontal.
Now you move one of these terminals down ($mod+Shift+j by default). The workspace node’s orientation will be changed to vertical. The terminal window you moved down is directly attached to the workspace and appears on the bottom of the screen. A new (horizontal) container was created to accommodate the other two terminal windows. You will notice this when switching to tabbed mode (for example). You would end up having one tab with a representation of the split container (e.g., "H[urxvt firefox]") and the other one being the terminal window you moved down.
4. Configuring i3
-----------------
This is where the real fun begins ;-). Most things are very dependent on your ideal working environment so we can’t make reasonable defaults for them.
While not using a programming language for the configuration, i3 stays quite flexible in regards to the things you usually want your window manager to do.
For example, you can configure bindings to jump to specific windows, you can set specific applications to start on specific workspaces, you can automatically start applications, you can change the colors of i3, and you can bind your keys to do useful things.
To change the configuration of i3, copy /etc/i3/config to ~/.i3/config (or ~/.config/i3/config if you like the XDG directory scheme) and edit it with a text editor.
On first start (and on all following starts, unless you have a configuration file), i3 will offer you to create a configuration file. You can tell the wizard to use either Alt (Mod1) or Windows (Mod4) as modifier in the config file. Also, the created config file will use the key symbols of your current keyboard layout. To start the wizard, use the command i3-config-wizard. Please note that you must not have ~/.i3/config, otherwise the wizard will exit.
Since i3 4.0, a new configuration format is used. i3 will try to automatically detect the format version of a config file based on a few different keywords, but if you want to make sure that your config is read with the new format, include the following line in your config file:
```
# i3 config file (v4)
```
### 4.1. Include directive
Since i3 v4.20, it is possible to include other configuration files from your i3 configuration.
**Syntax**:
```
include <pattern>
```
i3 expands pattern using shell-like word expansion, specifically using the [wordexp(3) C standard library function](https://manpages.debian.org/wordexp.3).
**Examples**:
```
# Tilde expands to the user’s home directory:
include ~/.config/i3/assignments.conf
# Environment variables are expanded:
include $HOME/.config/i3/assignments.conf
# Wildcards are expanded:
include ~/.config/i3/config.d/\*.conf
# Command substitution:
include ~/.config/i3/`hostname`.conf
# i3 loads each path only once, so including the i3 config will not result
# in an endless loop, but in an error:
include ~/.config/i3/config
# i3 changes the working directory while parsing a config file
# so that relative paths are interpreted relative to the directory
# of the config file that contains the path:
include assignments.conf
```
If a specified file cannot be read, for example because of a lack of file permissions, or because of a dangling symlink, i3 will report an error and continue processing your remaining configuration.
To list all loaded configuration files, run i3 --moreversion:
```
% i3 --moreversion
Binary i3 version: 4.19.2-87-gfcae64f7+ © 2009 Michael Stapelberg and contributors
Running i3 version: 4.19.2-87-gfcae64f7+ (pid 963940)
Loaded i3 config:
/tmp/i3.cfg (main) (last modified: 2021-05-13T16:42:31 CEST, 463 seconds ago)
/tmp/included.cfg (included) (last modified: 2021-05-13T16:42:43 CEST, 451 seconds ago)
/tmp/another.cfg (included) (last modified: 2021-05-13T16:42:46 CEST, 448 seconds ago)
```
Variables are shared between all config files, but beware of the following limitation:
* You can define a variable and use it within an included file.
* You cannot use (in the parent file) a variable that was defined within an included file.
This is a technical limitation: variable expansion happens in a separate stage before parsing include directives.
Conceptually, included files can only add to the configuration, not undo the effects of already-processed configuration. For example, you can only add new key bindings, not overwrite or remove existing key bindings. This means:
* The include directive is suitable for organizing large configurations into separate files, possibly selecting files based on conditionals.
* The include directive is not suitable for expressing “use the default configuration with the following changes”. For that case, we still recommend copying and modifying the default config.
| | |
| --- | --- |
| Note | Implementation-wise, i3 does not currently construct one big configuration from all include directives. Instead, i3’s config file parser interprets all configuration directives in its parse\_file() function. When processing an include configuration directive, the parser recursively calls parse\_file(). This means the evaluation order of files forms a tree, or one could say i3 uses depth-first traversal. |
### 4.2. Comments
It is possible and recommended to use comments in your configuration file to properly document your setup for later reference. Comments are started with a # and can only be used at the beginning of a line:
**Examples**:
```
# This is a comment
```
### 4.3. Fonts
i3 has support for both X core fonts and FreeType fonts (through Pango) to render window titles.
To generate an X core font description, you can use xfontsel(1). To see special characters (Unicode), you need to use a font which supports the ISO-10646 encoding.
A FreeType font description is composed by a font family, a style, a weight, a variant, a stretch and a size. FreeType fonts support right-to-left rendering and contain often more Unicode glyphs than X core fonts.
If i3 cannot open the configured font, it will output an error in the logfile and fall back to a working font.
**Syntax**:
```
font <X core font description>
font pango:<family list> [<style options>] <size>
```
**Examples**:
```
font -misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1
font pango:DejaVu Sans Mono 10
font pango:DejaVu Sans Mono, Terminus Bold Semi-Condensed 11
font pango:Terminus 11px
```
### 4.4. Keyboard bindings
A keyboard binding makes i3 execute a command (see below) upon pressing a specific key. i3 allows you to bind either on keycodes or on keysyms (you can also mix your bindings, though i3 will not protect you from overlapping ones).
* A keysym (key symbol) is a description for a specific symbol, like "a" or "b", but also more strange ones like "underscore" instead of "\_". These are the ones you use in Xmodmap to remap your keys. To get the current mapping of your keys, use xmodmap -pke. To interactively enter a key and see what keysym it is configured to, use xev.
* Keycodes do not need to have a symbol assigned (handy for custom vendor hotkeys on some notebooks) and they will not change their meaning as you switch to a different keyboard layout (when using xmodmap).
My recommendation is: If you often switch keyboard layouts but you want to keep your bindings in the same physical location on the keyboard, use keycodes. If you don’t switch layouts, and want a clean and simple config file, use keysyms.
Some tools (such as import or xdotool) might be unable to run upon a KeyPress event, because the keyboard/pointer is still grabbed. For these situations, the --release flag can be used, which will execute the command after the keys have been released.
**Syntax**:
```
bindsym [--release] [<Group>+][<Modifiers>+]<keysym> command
bindcode [--release] [<Group>+][<Modifiers>+]<keycode> command
```
**Examples**:
```
# Fullscreen
bindsym $mod+f fullscreen toggle
# Restart
bindsym $mod+Shift+r restart
# Notebook-specific hotkeys
bindcode 214 exec --no-startup-id /home/michael/toggle\_beamer.sh
# Simulate ctrl+v upon pressing $mod+x
bindsym --release $mod+x exec --no-startup-id xdotool key --clearmodifiers ctrl+v
# Take a screenshot upon pressing $mod+x (select an area)
bindsym --release $mod+x exec --no-startup-id import /tmp/latest-screenshot.png
```
Available Modifiers:
Mod1-Mod5, Shift, Control Standard modifiers, see xmodmap(1)
Group1, Group2, Group3, Group4 When using multiple keyboard layouts (e.g. with setxkbmap -layout us,ru), you can specify in which XKB group (also called “layout”) a keybinding should be active. By default, keybindings are translated in Group1 and are active in all groups. If you want to override keybindings in one of your layouts, specify the corresponding group. For backwards compatibility, the group “Mode\_switch” is an alias for Group2.
### 4.5. Mouse bindings
A mouse binding makes i3 execute a command upon pressing a specific mouse button in the scope of the clicked container (see [[command\_criteria]](#command_criteria)). You can configure mouse bindings in a similar way to key bindings.
**Syntax**:
```
bindsym [--release] [--border] [--whole-window] [--exclude-titlebar] [<Modifiers>+]button<n> command
```
By default, the binding will only run when you click on the titlebar of the window. If the --release flag is given, it will run when the mouse button is released.
If the --whole-window flag is given, the binding will also run when any part of the window is clicked, with the exception of the border. To have a bind run when the border is clicked, specify the --border flag.
If the --exclude-titlebar flag is given, the titlebar will not be considered for the keybinding.
**Examples**:
```
# The middle button over a titlebar kills the window
bindsym --release button2 kill
# The middle button and a modifier over any part of the window kills the window
bindsym --whole-window $mod+button2 kill
# The right button toggles floating
bindsym button3 floating toggle
bindsym $mod+button3 floating toggle
# The side buttons move the window around
bindsym button9 move left
bindsym button8 move right
```
### 4.6. Binding modes
You can have multiple sets of bindings by using different binding modes. When you switch to another binding mode, all bindings from the current mode are released and only the bindings defined in the new mode are valid for as long as you stay in that binding mode. The only predefined binding mode is default, which is the mode i3 starts out with and to which all bindings not defined in a specific binding mode belong.
Working with binding modes consists of two parts: defining a binding mode and switching to it. For these purposes, there are one config directive and one command, both of which are called mode. The directive is used to define the bindings belonging to a certain binding mode, while the command will switch to the specified mode.
It is recommended to use binding modes in combination with [[variables]](#variables) in order to make maintenance easier. Below is an example of how to use a binding mode.
Note that it is advisable to define bindings for switching back to the default mode.
Note that it is possible to use [[pango\_markup]](#pango_markup) for binding modes, but you need to enable it explicitly by passing the --pango\_markup flag to the mode definition.
**Syntax**:
```
# config directive
mode [--pango\_markup] <name>
# command
mode <name>
```
**Example**:
```
# Press $mod+o followed by either f, t, Escape or Return to launch firefox,
# thunderbird or return to the default mode, respectively.
set $mode\_launcher Launch: [f]irefox [t]hunderbird
bindsym $mod+o mode "$mode\_launcher"
mode "$mode\_launcher" {
bindsym f exec firefox
bindsym t exec thunderbird
bindsym Escape mode "default"
bindsym Return mode "default"
}
```
### 4.7. The floating modifier
To move floating windows with your mouse, you can either grab their titlebar or configure the so-called floating modifier which you can then press and click anywhere in the window itself to move it. The most common setup is to use the same key you use for managing windows (Mod1 for example). Then you can press Mod1, click into a window using your left mouse button, and drag it to the position you want.
When holding the floating modifier, you can resize a floating window by pressing the right mouse button on it and moving around while holding it. If you hold the shift button as well, the resize will be proportional (the aspect ratio will be preserved).
**Syntax**:
```
floating\_modifier <Modifier>
```
**Example**:
```
floating\_modifier Mod1
```
### 4.8. Constraining floating window size
The maximum and minimum dimensions of floating windows can be specified. If either dimension of floating\_maximum\_size is specified as -1, that dimension will be unconstrained with respect to its maximum value. If either dimension of floating\_maximum\_size is undefined, or specified as 0, i3 will use a default value to constrain the maximum size. floating\_minimum\_size is treated in a manner analogous to floating\_maximum\_size.
**Syntax**:
```
floating\_minimum\_size <width> x <height>
floating\_maximum\_size <width> x <height>
```
**Example**:
```
floating\_minimum\_size 75 x 50
floating\_maximum\_size -1 x -1
```
### 4.9. Orientation for new workspaces
New workspaces get a reasonable default orientation: Wide-screen monitors (anything wider than high) get horizontal orientation, rotated monitors (anything higher than wide) get vertical orientation.
With the default\_orientation configuration directive, you can override that behavior.
**Syntax**:
```
default\_orientation horizontal|vertical|auto
```
**Example**:
```
default\_orientation vertical
```
### 4.10. Layout mode for new containers
This option determines in which mode new containers on workspace level will start.
**Syntax**:
```
workspace\_layout default|stacking|tabbed
```
**Example**:
```
workspace\_layout tabbed
```
### 4.11. Window title alignment
This option determines the window title’s text alignment. Default is left
**Syntax**:
```
title\_align left|center|right
```
### 4.12. Default border style for new windows
This option determines which border style **new** windows will have. The default is normal. Note that default\_floating\_border applies only to windows which are starting out as floating windows, e.g., dialog windows, but not windows that are floated later on.
Setting border style to pixel eliminates title bars. The border style normal allows you to adjust edge border width while keeping your title bar.
**Syntax**:
```
default\_border normal|none|pixel
default\_border normal|pixel <px>
default\_floating\_border normal|none|pixel
default\_floating\_border normal|pixel <px>
```
Please note that new\_window and new\_float have been deprecated in favor of the above options and will be removed in a future release. We strongly recommend using the new options instead.
**Example**:
```
default\_border pixel
```
The "normal" and "pixel" border styles support an optional border width in pixels:
**Example**:
```
# The same as default\_border none
default\_border pixel 0
# A 3 px border
default\_border pixel 3
```
### 4.13. Hiding borders adjacent to the screen edges
You can hide container borders adjacent to the screen edges using hide\_edge\_borders (the default is none). Hiding borders is useful if you are using scrollbars, or do not want to waste even two pixels in displayspace.
The "smart" setting hides borders on workspaces with only one window visible, but keeps them on workspaces with multiple windows visible.
The "smart\_no\_gaps" setting hides edge-specific borders of a container if the container is the only container on its workspace and the gaps to the screen edge are 0.
**Syntax**:
```
hide\_edge\_borders none|vertical|horizontal|both|smart|smart\_no\_gaps
```
**Example**:
```
hide\_edge\_borders vertical
```
### 4.14. Smart borders
Smart borders will draw borders on windows only if there is more than one window in a workspace. This feature can also be enabled only if the gap size between window and screen edge is 0.
**Syntax**:
```
smart\_borders on|off|no\_gaps
```
**Example**:
```
# Activate smart borders (always)
smart\_borders on
# Activate smart borders (only when there are effectively no gaps)
smart\_borders no\_gaps
```
### 4.15. Arbitrary commands for specific windows (for\_window)
With the for\_window directive, you can let i3 execute any command when it encounters a specific window. This can be used to set windows to floating or to change their border style, for example.
**Syntax**:
```
for\_window <criteria> <command>
```
**Examples**:
```
# enable floating mode for all XTerm windows
for\_window [class="XTerm"] floating enable
# Make all urxvts use a 1-pixel border:
for\_window [class="urxvt"] border pixel 1
# A less useful, but rather funny example:
# makes the window floating as soon as I change
# directory to ~/work
for\_window [title="x200: ~/work"] floating enable
```
The valid criteria are the same as those for commands, see [[command\_criteria]](#command_criteria). Only commands can be executed at runtime, not config directives, see [[list\_of\_commands]](#list_of_commands).
### 4.16. Don’t focus window upon opening
When a new window appears, it will be focused. The no\_focus directive allows preventing this from happening and must be used in combination with [[command\_criteria]](#command_criteria).
Note that this does not apply to all cases, e.g., when feeding data into a running application causing it to request being focused. To configure the behavior in such cases, refer to [[focus\_on\_window\_activation]](#focus_on_window_activation).
no\_focus will also be ignored for the first window on a workspace as there shouldn’t be a reason to not focus the window in this case. This allows for better usability in combination with workspace\_layout.
**Syntax**:
```
no\_focus <criteria>
```
**Example**:
```
no\_focus [window\_role="pop-up"]
```
### 4.17. Variables
As you learned in the section about keyboard bindings, you will have to configure lots of bindings containing modifier keys. If you want to save yourself some typing and be able to change the modifier you use later, variables can be handy.
**Syntax**:
```
set $<name> <value>
```
**Example**:
```
set $m Mod1
bindsym $m+Shift+r restart
```
Variables are directly replaced in the file when parsing. Variables expansion is not recursive so it is not possible to define a variable with a value containing another variable. There is no fancy handling and there are absolutely no plans to change this. If you need a more dynamic configuration you should create a little script which generates a configuration file and run it before starting i3 (for example in your ~/.xsession file).
Also see [[xresources]](#xresources) to learn how to create variables based on resources loaded from the X resource database.
### 4.18. X resources
[[variables]](#variables) can also be created using a value configured in the X resource database. This is useful, for example, to avoid configuring color values within the i3 configuration. Instead, the values can be configured, once, in the X resource database to achieve an easily maintainable, consistent color theme across many X applications.
Defining a resource will load this resource from the resource database and assign its value to the specified variable. This is done verbatim and the value must therefore be in the format that i3 uses. A fallback must be specified in case the resource cannot be loaded from the database.
**Syntax**:
```
set\_from\_resource $<name> <resource\_name> <fallback>
```
**Example**:
```
# The ~/.Xresources should contain a line such as
# \*color0: #121212
# and must be loaded properly, e.g., by using
# xrdb ~/.Xresources
# This value is picked up on by other applications (e.g., the URxvt terminal
# emulator) and can be used in i3 like this:
set\_from\_resource $black i3wm.color0 #000000
```
### 4.19. Automatically putting clients on specific workspaces
To automatically make a specific window show up on a specific workspace, you can use an **assignment**. You can match windows by using any criteria, see [[command\_criteria]](#command_criteria). The difference between assign and for\_window <criteria> move to workspace is that the former will only be executed when the application maps the window (mapping means actually displaying it on the screen) but the latter will be executed whenever a window changes its properties to something that matches the specified criteria.
Thus, it is recommended that you match on window classes (and instances, when appropriate) instead of window titles whenever possible because some applications first create their window, and then worry about setting the correct title. Firefox with Vimperator comes to mind. The window starts up being named Firefox, and only when Vimperator is loaded does the title change. As i3 will get the title as soon as the application maps the window, you’d need to have to match on *Firefox* in this case. Another known issue is with Spotify, which doesn’t set the class hints when mapping the window, meaning you’ll have to use a for\_window rule to assign Spotify to a specific workspace. Finally, using assign [tiling] and assign [floating] is not supported.
You can also assign a window to show up on a specific output. You can use RandR names such as VGA1 or names relative to the output with the currently focused workspace such as left and down.
Assignments are processed by i3 in the order in which they appear in the config file. The first one which matches the window wins and later assignments are not considered.
**Syntax**:
```
assign <criteria> [→] [workspace] [number] <workspace>
assign <criteria> [→] output left|right|up|down|primary|nonprimary|<output>
```
**Examples**:
```
# Assign URxvt terminals to workspace 2
assign [class="URxvt"] 2
# Same thing, but more precise (exact match instead of substring)
assign [class="^URxvt$"] 2
# Same thing, but with a beautiful arrow :)
assign [class="^URxvt$"] → 2
# Assignment to a named workspace
assign [class="^URxvt$"] → work
# Assign to the workspace with number 2, regardless of name
assign [class="^URxvt$"] → number 2
# You can also specify a number + name. If the workspace with number 2 exists,
# assign will skip the text part.
assign [class="^URxvt$"] → number "2: work"
# Start urxvt -name irssi
assign [class="^URxvt$" instance="^irssi$"] → 3
# Assign urxvt to the output right of the current one
assign [class="^URxvt$"] → output right
# Assign urxvt to the primary output
assign [class="^URxvt$"] → output primary
# Assign urxvt to the first non-primary output
assign [class="^URxvt$"] → output nonprimary
```
Note that you might not have a primary output configured yet. To do so, run:
```
xrandr --output <output> --primary
```
Also, the arrow is not required, it just looks good :-). If you decide to use it, it has to be a UTF-8 encoded arrow, not -> or something like that.
To get the class and instance, you can use xprop. After clicking on the window, you will see the following output:
**xprop**:
```
WM\_CLASS(STRING) = "irssi", "URxvt"
```
The first part of the WM\_CLASS is the instance ("irssi" in this example), the second part is the class ("URxvt" in this example).
Should you have any problems with assignments, make sure to check the i3 logfile first (see <https://i3wm.org/docs/debugging.html>). It includes more details about the matching process and the window’s actual class, instance and title when starting up.
Note that if you want to start an application just once on a specific workspace, but you don’t want to assign all instances of it permanently, you can make use of i3’s startup-notification support (see [[exec]](#exec)) in your config file in the following way:
**Start iceweasel on workspace 3 (once)**:
```
# Start iceweasel on workspace 3, then switch back to workspace 1
# (Being a command-line utility, i3-msg does not support startup notifications,
# hence the exec --no-startup-id.)
# (Starting iceweasel with i3’s exec command is important in order to make i3
# create a startup notification context, without which the iceweasel window(s)
# cannot be matched onto the workspace on which the command was started.)
exec --no-startup-id i3-msg 'workspace 3; exec iceweasel; workspace 1'
```
### 4.20. Automatically starting applications on i3 startup
By using the exec keyword outside a keybinding, you can configure which commands will be performed by i3 on initial startup. exec commands will not run when restarting i3, if you need a command to run also when restarting i3 you should use the exec\_always keyword. These commands will be run in order.
See [[command\_chaining]](#command_chaining) for details on the special meaning of ; (semicolon) and , (comma): they chain commands together in i3, so you need to use quoted strings (as shown in [[exec\_quoting]](#exec_quoting)) if they appear in your command.
**Syntax**:
```
exec [--no-startup-id] <command>
exec\_always [--no-startup-id] <command>
```
**Examples**:
```
exec chromium
exec\_always ~/my\_script.sh
# Execute the terminal emulator urxvt, which is not yet startup-notification aware.
exec --no-startup-id urxvt
```
The flag --no-startup-id is explained in [[exec]](#exec).
### 4.21. Automatically putting workspaces on specific screens
If you assign clients to workspaces, it might be handy to put the workspaces on specific screens. Also, the assignment of workspaces to screens will determine which workspace i3 uses for a new screen when adding screens or when starting (e.g., by default it will use 1 for the first screen, 2 for the second screen and so on).
**Syntax**:
```
workspace <workspace> output <output1> [output2]…
```
The *output* is the name of the RandR output you attach your screen to. On a laptop, you might have VGA1 and LVDS1 as output names. You can see the available outputs by running xrandr --current.
If your X server supports RandR 1.5 or newer, i3 will use RandR monitor objects instead of output objects. Run xrandr --listmonitors to see a list. Usually, a monitor object contains exactly one output, and has the same name as the output; but should that not be the case, you can specify the name of either the monitor or the output in i3’s configuration. For example, the Dell UP2414Q uses two scalers internally, so its output names might be “DP1” and “DP2”, but the monitor name is “Dell UP2414Q”.
(Note that even if you specify the name of an output which doesn’t span the entire monitor, i3 will still use the entire area of the containing monitor rather than that of just the output’s.)
You can specify multiple outputs. The first available will be used.
If you use named workspaces, they must be quoted:
**Examples**:
```
workspace 1 output LVDS1
workspace 2 output primary
workspace 5 output VGA1 LVDS1
workspace "2: vim" output VGA1
```
### 4.22. Changing colors
You can change all colors which i3 uses to draw the window decorations.
**Syntax**:
```
<colorclass> <border> <background> <text> <indicator> <child\_border>
```
Where colorclass can be one of:
client.focused A client which currently has the focus.
client.focused\_inactive A client which is the focused one of its container, but it does not have the focus at the moment.
client.focused\_tab\_title Tab or stack container title that is the parent of the focused container but not directly focused. Defaults to focused\_inactive if not specified and does not use the indicator and child\_border colors.
client.unfocused A client which is not the focused one of its container.
client.urgent A client which has its urgency hint activated.
client.placeholder Background and text color are used to draw placeholder window contents (when restoring layouts). Border and indicator are ignored.
client.background Background color which will be used to paint the background of the client window on top of which the client will be rendered. Only clients which do not cover the whole area of this window expose the color. Note that this colorclass only takes a single color.
Colors are in HTML hex format (#rrggbb, optionally #rrggbbaa), see the following example:
**Examples (default colors)**:
```
# class border backgr. text indicator child\_border
client.focused #4c7899 #285577 #ffffff #2e9ef4 #285577
client.focused\_inactive #333333 #5f676a #ffffff #484e50 #5f676a
client.unfocused #333333 #222222 #888888 #292d2e #222222
client.urgent #2f343a #900000 #ffffff #900000 #900000
client.placeholder #000000 #0c0c0c #ffffff #000000 #0c0c0c
client.background #ffffff
```
Note that for the window decorations, the color around the child window is the "child\_border", and "border" color is only the two thin lines around the titlebar.
The indicator color is used for indicating where a new window will be opened. For horizontal split containers, the right border will be painted in indicator color, for vertical split containers, the bottom border. This only applies to single windows within a split container, which are otherwise indistinguishable from single windows outside of a split container.
### 4.23. Interprocess communication
i3 uses Unix sockets to provide an IPC interface. This allows third-party programs to get information from i3, such as the current workspaces (to display a workspace bar), and to control i3.
By default, an IPC socket will be created in $XDG\_RUNTIME\_DIR/i3/ipc-socket.%p if the directory is available, falling back to /tmp/i3-%u.XXXXXX/ipc-socket.%p, where %u is your UNIX username, %p is the PID of i3 and XXXXXX is a string of random characters from the portable filename character set (see mkdtemp(3)).
You can override the default path through the environment-variable I3SOCK or by specifying the ipc-socket directive. This is discouraged, though, since i3 does the right thing by default. If you decide to change it, it is strongly recommended to set this to a location in your home directory so that no other user can create that directory.
**Examples**:
```
ipc-socket ~/.i3/i3-ipc.sock
```
You can then use the i3-msg application to perform any command listed in [[list\_of\_commands]](#list_of_commands).
### 4.24. Focus follows mouse
By default, window focus follows your mouse movements as the mouse crosses window borders. However, if you have a setup where your mouse usually is in your way (like a touchpad on your laptop which you do not want to disable completely), you might want to disable *focus follows mouse* and control focus only by using your keyboard. The mouse will still be useful inside the currently active window (for example to click on links in your browser window).
**Syntax**:
```
focus\_follows\_mouse yes|no
```
**Example**:
```
focus\_follows\_mouse no
```
### 4.25. Mouse warping
By default, when switching focus to a window on a different output (e.g. focusing a window on workspace 3 on output VGA-1, coming from workspace 2 on LVDS-1), the mouse cursor is warped to the center of that window.
With the mouse\_warping option, you can control when the mouse cursor should be warped. none disables warping entirely, whereas output is the default behavior described above.
**Syntax**:
```
mouse\_warping output|none
```
**Example**:
```
mouse\_warping none
```
### 4.26. Popups during fullscreen mode
When you are in fullscreen mode, some applications still open popup windows (take Xpdf for example). This is because these applications might not be aware that they are in fullscreen mode (they do not check the corresponding hint). There are three things which are possible to do in this situation:
1. Display the popup if it belongs to the fullscreen application only. This is the default and should be reasonable behavior for most users.
2. Just ignore the popup (don’t map it). This won’t interrupt you while you are in fullscreen. However, some apps might react badly to this (deadlock until you go out of fullscreen).
3. Leave fullscreen mode.
**Syntax**:
```
popup\_during\_fullscreen smart|ignore|leave\_fullscreen
```
**Example**:
```
popup\_during\_fullscreen smart
```
### 4.27. Focus wrapping
By default, when in a container with several windows or child containers, the opposite window will be focused when trying to move the focus over the edge of a container (and there are no other containers in that direction) — the focus wraps.
If desired, you can disable this behavior by setting the focus\_wrapping configuration directive to the value no.
When enabled, focus wrapping does not occur by default if there is another window or container in the specified direction, and focus will instead be set on that window or container. This is the default behavior so you can navigate to all your windows without having to use focus parent.
If you want the focus to **always** wrap and you are aware of using focus parent to switch to different containers, you can instead set focus\_wrapping to the value force.
To restrict focus inside the current workspace set focus\_wrapping to the value workspace. You will need to use focus parent until a workspace is selected to switch to a different workspace using the focus commands (the workspace command will still work as expected).
**Syntax**:
```
focus\_wrapping yes|no|force|workspace
# Legacy syntax, equivalent to "focus\_wrapping force"
force\_focus\_wrapping yes
```
**Examples**:
```
# Disable focus wrapping
focus\_wrapping no
# Force focus wrapping
focus\_wrapping force
```
### 4.28. Forcing Xinerama
As explained in-depth in <https://i3wm.org/docs/multi-monitor.html>, some X11 video drivers (especially the nVidia binary driver) only provide support for Xinerama instead of RandR. In such a situation, i3 must be told to use the inferior Xinerama API explicitly and therefore don’t provide support for reconfiguring your screens on the fly (they are read only once on startup and that’s it).
For people who cannot modify their ~/.xsession to add the --force-xinerama commandline parameter, a configuration option is provided:
**Syntax**:
```
force\_xinerama yes|no
```
**Example**:
```
force\_xinerama yes
```
Also note that your output names are not descriptive (like HDMI1) when using Xinerama, instead they are counted up, starting at 0: xinerama-0, xinerama-1, …
### 4.29. Automatic back-and-forth when switching to the current workspace
This configuration directive enables automatic workspace back\_and\_forth (see [[back\_and\_forth]](#back_and_forth)) when switching to the workspace that is currently focused.
For instance: Assume you are on workspace "1: www" and switch to "2: IM" using mod+2 because somebody sent you a message. You don’t need to remember where you came from now, you can just press $mod+2 again to switch back to "1: www".
**Syntax**:
```
workspace\_auto\_back\_and\_forth yes|no
```
**Example**:
```
workspace\_auto\_back\_and\_forth yes
```
### 4.30. Delaying urgency hint reset on workspace change
If an application on another workspace sets an urgency hint, switching to this workspace might lead to immediate focus of the application, which also means the window decoration color would be immediately reset to client.focused. This might make it unnecessarily hard to tell which window originally raised the event.
In order to prevent this, you can tell i3 to delay resetting the urgency state by a certain time using the force\_display\_urgency\_hint directive. Setting the value to 0 disables this feature.
The default is 500ms.
**Syntax**:
```
force\_display\_urgency\_hint <timeout> ms
```
**Example**:
```
force\_display\_urgency\_hint 500 ms
```
### 4.31. Focus on window activation
If a window is activated, e.g., via google-chrome www.google.com, it may request to take focus. Since this might not be preferable, different reactions can be configured.
Note that this might not affect windows that are being opened. To prevent new windows from being focused, see [[no\_focus]](#no_focus).
**Syntax**:
```
focus\_on\_window\_activation smart|urgent|focus|none
```
The different modes will act as follows:
smart This is the default behavior. If the window requesting focus is on an active workspace, it will receive the focus. Otherwise, the urgency hint will be set.
urgent The window will always be marked urgent, but the focus will not be stolen.
focus The window will always be focused and not be marked urgent.
none The window will neither be focused, nor be marked urgent.
### 4.32. Drawing marks on window decoration
If activated, marks (see [[vim\_like\_marks]](#vim_like_marks)) on windows are drawn in their window decoration. However, any mark starting with an underscore in its name (\_) will not be drawn even if this option is activated.
The default for this option is yes.
**Syntax**:
```
show\_marks yes|no
```
**Example**:
```
show\_marks yes
```
### 4.33. Line continuation
Config files support line continuation, meaning when you end a line in a backslash character (\), the line-break will be ignored by the parser. This feature can be used to create more readable configuration files. Commented lines are not continued.
**Examples**:
```
bindsym Mod1+f \
fullscreen toggle
# this line is not continued \
bindsym Mod1+F fullscreen toggle
```
### 4.34. Tiling drag
You can configure how to initiate the tiling drag feature (see [[tiling\_drag]](#tiling_drag)).
**Syntax**:
```
tiling\_drag off
tiling\_drag modifier|titlebar [modifier|titlebar]
```
**Examples**:
```
# Only initiate a tiling drag when the modifier is held:
tiling\_drag modifier
# Initiate a tiling drag on either titlebar click or held modifier:
tiling\_drag modifier titlebar
# Disable tiling drag altogether
tiling\_drag off
```
### 4.35. Gaps
Since i3 4.22, you can configure window gaps. “Gaps” are added spacing between windows (or split containers) and to the screen edges:
Figure 5. Gaps enabled (10 px inner gaps, 20 px outer gaps) You can configure two different kind of gaps:
1. Inner gaps are space between two adjacent windows (or split containers).
2. Outer gaps are space along the screen edges. You can configure each side (left, right, top, bottom) separately.
If you are familiar with HTML and CSS, you can think of inner gaps as padding, and of outer gaps as margin, applied to a <div> around your window or split container.
Note that outer gaps are added to the inner gaps, meaning the total gap size between a screen edge and a window (or split container) will be the sum of outer and inner gaps.
You can define gaps either globally or per workspace using the following syntax.
**Syntax**:
```
# Inner gaps for all windows: space between two adjacent windows (or split containers).
gaps inner <gap\_size>[px]
# Outer gaps for all windows: space along the screen edges.
gaps outer|horizontal|vertical|top|left|bottom|right <gap\_size>[px]
# Inner and outer gaps for all windows on a specific workspace.
# <ws> can be a workspace number or name.
workspace <ws> gaps inner <gap\_size>[px]
workspace <ws> gaps outer|horizontal|vertical|top|left|bottom|right <gap\_size>[px]
# Enabling “Smart Gaps” means no gaps will be shown when there is
# precisely one window or split container on the workspace.
#
# inverse\_outer only enables outer gaps when there is exactly one
# window or split container on the workspace.
smart\_gaps on|off|inverse\_outer
```
Outer gaps can be configured for each side individually with the top, left, bottom and right directive. horizontal and vertical are shortcuts for left/right and top/bottom, respectively.
**Example**:
```
# Configure 5px of space between windows and to the screen edges.
gaps inner 5px
# Configure an additional 5px of extra space to the screen edges,
# for a total gap of 10px to the screen edges, and 5px between windows.
gaps outer 5px
# Overwrite gaps to 0, I need all the space I can get on workspace 3.
workspace 3 gaps inner 0
workspace 3 gaps outer 0
# Only enable outer gaps when there is exactly one window or split container on the workspace.
smart\_gaps inverse\_outer
```
Tip: Gaps can additionally be changed at runtime with the gaps command, see [[changing\_gaps]](#changing_gaps).
Tip: You can find an [example configuration](https://github.com/Airblader/i3/wiki/Example-Configuration) that uses modes to illustrate various gap configurations.
5. Configuring i3bar
--------------------
The bar at the bottom of your monitor is drawn by a separate process called i3bar. Having this part of "the i3 user interface" in a separate process has several advantages:
1. It is a modular approach. If you don’t need a workspace bar at all, or if you prefer a different one (dzen2, xmobar, maybe even gnome-panel?), you can just remove the i3bar configuration and start your favorite bar instead.
2. It follows the UNIX philosophy of "Make each program do one thing well". While i3 manages your windows well, i3bar is good at displaying a bar on each monitor (unless you configure it otherwise).
3. It leads to two separate, clean codebases. If you want to understand i3, you don’t need to bother with the details of i3bar and vice versa.
That said, i3bar is configured in the same configuration file as i3. This is because it is tightly coupled with i3 (in contrary to i3lock or i3status which are useful for people using other window managers). Therefore, it makes no sense to use a different configuration place when we already have a good configuration infrastructure in place.
Configuring your workspace bar starts with opening a bar block. You can have multiple bar blocks to use different settings for different outputs (monitors):
**Example**:
```
bar {
status\_command i3status
}
```
### 5.1. i3bar command
By default i3 will just pass i3bar and let your shell handle the execution, searching your $PATH for a correct version. If you have a different i3bar somewhere or the binary is not in your $PATH you can tell i3 what to execute.
The specified command will be passed to sh -c, so you can use globbing and have to have correct quoting etc.
**Syntax**:
```
i3bar\_command <command>
```
**Example**:
```
bar {
i3bar\_command /home/user/bin/i3bar
}
```
### 5.2. Statusline command
i3bar can run a program and display every line of its stdout output on the right hand side of the bar. This is useful to display system information like your current IP address, battery status or date/time.
The specified command will be passed to sh -c, so you can use globbing and have to have correct quoting etc. Note that for signal handling, depending on your shell (users of dash(1) are known to be affected), you have to use the shell’s exec command so that signals are passed to your program, not to the shell.
**Syntax**:
```
status\_command <command>
```
**Example**:
```
bar {
status\_command i3status --config ~/.i3status.conf
# For dash(1) users who want signal handling to work:
status\_command exec ~/.bin/my\_status\_command
}
```
### 5.3. Display mode
You can either have i3bar be visible permanently at one edge of the screen (dock mode) or make it show up when you press your modifier key (hide mode). It is also possible to force i3bar to always stay hidden (invisible mode). The modifier key can be configured using the modifier option.
The mode option can be changed during runtime through the bar mode command. On reload the mode will be reverted to its configured value.
The hide mode maximizes screen space that can be used for actual windows. When the bar is hidden, i3bar sends the SIGSTOP and SIGCONT signals to the status\_command process in order to conserve battery power. This feature can be disabled by the status\_command process by setting the appropriate values in its JSON header message.
Invisible mode allows to permanently maximize screen space, as the bar is never shown. Thus, you can configure i3bar to not disturb you by popping up because of an urgency hint or because the modifier key is pressed.
In order to control whether i3bar is hidden or shown in hide mode, there exists the hidden\_state option, which has no effect in dock mode or invisible mode. It indicates the current hidden\_state of the bar: (1) The bar acts like in normal hide mode, it is hidden and is only unhidden in case of urgency hints or by pressing the modifier key (hide state), or (2) it is drawn on top of the currently visible workspace (show state).
Like the mode, the hidden\_state can also be controlled through i3, this can be done by using the bar hidden\_state command.
The default mode is dock mode; in hide mode, the default modifier is Mod4 (usually the windows key). The default value for the hidden\_state is hide.
**Syntax**:
```
mode dock|hide|invisible
hidden\_state hide|show
modifier <Modifier>|none
```
**Example**:
```
bar {
mode hide
hidden\_state hide
modifier Mod1
}
```
Available modifiers are Mod1-Mod5, Shift, Control (see xmodmap(1)). You can also use "none" if you don’t want any modifier to trigger this behavior.
### 5.4. Mouse button commands
Specifies a command to run when a button was pressed on i3bar to override the default behavior. This is useful, e.g., for disabling the scroll wheel action or running scripts that implement custom behavior for these buttons.
A button is always named button<n>, where 1 to 5 are default buttons as follows and higher numbers can be special buttons on devices offering more buttons:
button1 Left mouse button.
button2 Middle mouse button.
button3 Right mouse button.
button4 Scroll wheel up.
button5 Scroll wheel down.
button6 Scroll wheel right.
button7 Scroll wheel left.
Please note that the old wheel\_up\_cmd and wheel\_down\_cmd commands are deprecated and will be removed in a future release. We strongly recommend using the more general bindsym with button4 and button5 instead.
**Syntax**:
```
bindsym [--release] button<n> <command>
```
**Example**:
```
bar {
# disable clicking on workspace buttons
bindsym button1 nop
# Take a screenshot by right clicking on the bar
bindsym --release button3 exec --no-startup-id import /tmp/latest-screenshot.png
# execute custom script when scrolling downwards
bindsym button5 exec ~/.i3/scripts/custom\_wheel\_down
}
```
### 5.5. Bar ID
Specifies the bar ID for the configured bar instance. If this option is missing, the ID is set to *bar-x*, where x corresponds to the position of the embedding bar block in the config file (*bar-0*, *bar-1*, …).
**Syntax**:
```
id <bar\_id>
```
**Example**:
```
bar {
id bar-1
}
```
### 5.6. Position
This option determines in which edge of the screen i3bar should show up.
The default is bottom.
**Syntax**:
```
position top|bottom
```
**Example**:
```
bar {
position top
}
```
### 5.7. Output(s)
You can restrict i3bar to one or more outputs (monitors). The default is to handle all outputs. Restricting the outputs is useful for using different options for different outputs by using multiple *bar* blocks.
To make a particular i3bar instance handle multiple outputs, specify the output directive multiple times.
These output names have a special meaning:
primary Selects the output that is configured as primary in the X server.
nonprimary Selects every output that is not configured as primary in the X server.
**Syntax**:
```
output primary|nonprimary|<output>
```
**Example**:
```
# big monitor: everything
bar {
# The display is connected either via HDMI or via DisplayPort
output HDMI2
output DP2
status\_command i3status
}
# laptop monitor: bright colors and i3status with less modules.
bar {
output LVDS1
status\_command i3status --config ~/.i3status-small.conf
colors {
background #000000
statusline #ffffff
}
}
# show bar on the primary monitor and on HDMI2
bar {
output primary
output HDMI2
status\_command i3status
}
```
Note that you might not have a primary output configured yet. To do so, run:
```
xrandr --output <output> --primary
```
### 5.8. Tray output
i3bar by default provides a system tray area where programs such as NetworkManager, VLC, Pidgin, etc. can place little icons.
You can configure on which output (monitor) the icons should be displayed or you can turn off the functionality entirely.
You can use multiple tray\_output directives in your config to specify a list of outputs on which you want the tray to appear. The first available output in that list as defined by the order of the directives will be used for the tray output.
**Syntax**:
```
tray\_output none|primary|<output>
```
**Example**:
```
# disable system tray
bar {
tray\_output none
}
# show tray icons on the primary monitor
bar {
tray\_output primary
}
# show tray icons on the big monitor
bar {
tray\_output HDMI2
}
```
Note that you might not have a primary output configured yet. To do so, run:
```
xrandr --output <output> --primary
```
Note that when you use multiple bar configuration blocks, either specify tray\_output primary in all of them or explicitly specify tray\_output none in bars which should not display the tray, otherwise the different instances might race each other in trying to display tray icons.
### 5.9. Tray padding
The tray is shown on the right-hand side of the bar. By default, a padding of 2 pixels is used for the upper, lower and right-hand side of the tray area and between the individual icons.
**Syntax**:
```
tray\_padding <px> [px]
```
**Example**:
```
# Obey Fitts's law
tray\_padding 0
```
### 5.10. Font
Specifies the font to be used in the bar. See [[fonts]](#fonts).
**Syntax**:
```
font <font>
```
**Example**:
```
bar {
font -misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1
font pango:DejaVu Sans Mono 10
}
```
### 5.11. Custom separator symbol
Specifies a custom symbol to be used for the separator as opposed to the vertical, one pixel thick separator.
**Syntax**:
```
separator\_symbol <symbol>
```
**Example**:
```
bar {
separator\_symbol ":|:"
}
```
### 5.12. Workspace buttons
Specifies whether workspace buttons should be shown or not. This is useful if you want to display a statusline-only bar containing additional information.
The default is to show workspace buttons.
**Syntax**:
```
workspace\_buttons yes|no
```
**Example**:
```
bar {
workspace\_buttons no
}
```
### 5.13. Minimal width for workspace buttons
By default, the width a workspace button is determined by the width of the text showing the workspace name. If the name is too short (say, one letter), then the workspace button might look too small.
This option specifies the minimum width for workspace buttons. If the name of a workspace is too short to cover the button, an additional padding is added on both sides of the button so that the text is centered.
The default value of zero means that no additional padding is added.
The setting also applies to the current binding mode indicator.
Note that the specified pixels refer to logical pixels, which might translate into more pixels on HiDPI displays.
**Syntax**:
```
workspace\_min\_width <px> [px]
```
**Example**:
```
bar {
workspace\_min\_width 40
}
```
### 5.14. Strip workspace numbers/name
Specifies whether workspace numbers should be displayed within the workspace buttons. This is useful if you want to have a named workspace that stays in order on the bar according to its number without displaying the number prefix.
When strip\_workspace\_numbers is set to yes, any workspace that has a name of the form "[n][:][NAME]" will display only the name. You could use this, for instance, to display Roman numerals rather than digits by naming your workspaces to "1:I", "2:II", "3:III", "4:IV", …
When strip\_workspace\_name is set to yes, any workspace that has a name of the form "[n][:][NAME]" will display only the number.
The default is to display the full name within the workspace button. Be aware that the colon in the workspace name is optional, so [n][NAME] will also have the workspace name and number stripped correctly.
**Syntax**:
```
strip\_workspace\_numbers yes|no
strip\_workspace\_name yes|no
```
**Example**:
```
bar {
strip\_workspace\_numbers yes
}
```
### 5.15. Binding Mode indicator
Specifies whether the current binding mode indicator should be shown or not. This is useful if you want to hide the workspace buttons but still be able to see the current binding mode indicator. See [[binding\_modes]](#binding_modes) to learn what modes are and how to use them.
The default is to show the mode indicator.
**Syntax**:
```
binding\_mode\_indicator yes|no
```
**Example**:
```
bar {
binding\_mode\_indicator no
}
```
### 5.16. Colors
As with i3, colors are in HTML hex format (#rrggbb, optionally #rrggbbaa). The following colors can be configured at the moment:
background Background color of the bar.
statusline Text color to be used for the statusline.
separator Text color to be used for the separator.
focused\_background Background color of the bar on the currently focused monitor output. If not used, the color will be taken from background.
focused\_statusline Text color to be used for the statusline on the currently focused monitor output. If not used, the color will be taken from statusline.
focused\_separator Text color to be used for the separator on the currently focused monitor output. If not used, the color will be taken from separator.
focused\_workspace Border, background and text color for a workspace button when the workspace has focus.
active\_workspace Border, background and text color for a workspace button when the workspace is active (visible) on some output, but the focus is on another one. You can only tell this apart from the focused workspace when you are using multiple monitors.
inactive\_workspace Border, background and text color for a workspace button when the workspace does not have focus and is not active (visible) on any output. This will be the case for most workspaces.
urgent\_workspace Border, background and text color for a workspace button when the workspace contains a window with the urgency hint set.
binding\_mode Border, background and text color for the binding mode indicator. If not used, the colors will be taken from urgent\_workspace.
**Syntax**:
```
colors {
background <color>
statusline <color>
separator <color>
<colorclass> <border> <background> <text>
}
```
**Example (default colors)**:
```
bar {
colors {
background #000000
statusline #ffffff
separator #666666
focused\_workspace #4c7899 #285577 #ffffff
active\_workspace #333333 #5f676a #ffffff
inactive\_workspace #333333 #222222 #888888
urgent\_workspace #2f343a #900000 #ffffff
binding\_mode #2f343a #900000 #ffffff
}
}
```
### 5.17. Transparency
i3bar can support transparency by passing the --transparency flag in the configuration:
**Syntax**:
```
bar {
i3bar\_command i3bar --transparency
}
```
In the i3bar color configuration and i3bar status block color attribute you can then use colors in the RGBA format, i.e. the last two (hexadecimal) digits specify the opacity. For example, #00000000 will be completely transparent, while #000000FF will be a fully opaque black (the same as #000000).
Please note that due to the way the tray specification works, enabling this flag will cause all tray icons to have a transparent background.
### 5.18. Padding
To make i3bar higher (without increasing the font size), and/or add padding to the left and right side of i3bar, you can use the padding directive:
**Syntax**:
```
bar {
# 2px left/right and 2px top/bottom padding
padding 2px
# 2px top/bottom padding, no left/right padding
padding 2px 0
# 2px top padding, no left/right padding, 4px bottom padding
padding 2px 0 4px
# four value syntax
padding top[px] right[px] bottom[px] left[px]
}
```
**Examples**:
```
bar {
# 2px left/right and 2px top/bottom padding
padding 2px
# 2px top/bottom padding, no left/right padding
padding 2px 0
# 2px top padding, no left/right padding, 4px bottom padding
padding 2px 0 4px
# 2px top padding, 6px right padding, 4px bottom padding, 1px left padding
padding 2px 6px 4px 1px
}
```
Note: As a convenience for users who migrate from i3-gaps to i3, the height directive from i3-gaps is supported by i3, but should be changed to padding.
6. List of commands
-------------------
Commands are what you bind to specific keypresses. You can also issue commands at runtime without pressing a key by using the IPC interface. An easy way to do this is to use the i3-msg utility:
**Example**:
```
# execute this on your shell to make the current container borderless
i3-msg border none
```
Commands can be chained by using ; (a semicolon). So, to move a window to a specific workspace and immediately switch to that workspace, you can configure the following keybinding:
**Example**:
```
bindsym $mod+x move container to workspace 3; workspace 3
```
Furthermore, you can change the scope of a command - that is, which containers should be affected by that command, by using various criteria. The criteria are specified before any command in a pair of square brackets and are separated by space.
When using multiple commands, separate them by using a , (a comma) instead of a semicolon. Criteria apply only until the next semicolon, so if you use a semicolon to separate commands, only the first one will be executed for the matched window(s).
**Example**:
```
# if you want to kill all windows which have the class Firefox, use:
bindsym $mod+x [class="Firefox"] kill
# same thing, but case-insensitive
bindsym $mod+x [class="(?i)firefox"] kill
# kill only the About dialog from Firefox
bindsym $mod+x [class="Firefox" window\_role="About"] kill
# enable floating mode and move container to workspace 4
for\_window [class="^evil-app$"] floating enable, move container to workspace 4
# enable window icons for all windows with extra horizontal padding of 1px
for\_window [all] title\_window\_icon padding 1px
# move all floating windows to the scratchpad
bindsym $mod+x [floating] move scratchpad
```
The criteria which are currently implemented are:
all Matches all windows. This criterion requires no value.
class Compares the window class (the second part of WM\_CLASS). Use the special value \_\_focused\_\_ to match all windows having the same window class as the currently focused window.
instance Compares the window instance (the first part of WM\_CLASS). Use the special value \_\_focused\_\_ to match all windows having the same window instance as the currently focused window.
window\_role Compares the window role (WM\_WINDOW\_ROLE). Use the special value \_\_focused\_\_ to match all windows having the same window role as the currently focused window.
window\_type Compare the window type (\_NET\_WM\_WINDOW\_TYPE). Possible values are normal, dialog, utility, toolbar, splash, menu, dropdown\_menu, popup\_menu, tooltip and notification.
machine Compares the name of the machine the client window is running on (WM\_CLIENT\_MACHINE). Usually, it is equal to the hostname of the local machine, but it may differ if remote X11 apps are used.
id Compares the X11 window ID, which you can get via xwininfo for example.
title Compares the X11 window title (\_NET\_WM\_NAME or WM\_NAME as fallback). Use the special value \_\_focused\_\_ to match all windows having the same window title as the currently focused window.
urgent Compares the urgent state of the window. Can be "latest" or "oldest". Matches the latest or oldest urgent window, respectively. (The following aliases are also available: newest, last, recent, first)
workspace Compares the workspace name of the workspace the window belongs to. Use the special value \_\_focused\_\_ to match all windows in the currently focused workspace.
con\_mark Compares the marks set for this container, see [[vim\_like\_marks]](#vim_like_marks). A match is made if any of the container’s marks matches the specified mark.
con\_id Compares the i3-internal container ID, which you can get via the IPC interface. Handy for scripting. Use the special value \_\_focused\_\_ to match only the currently focused window.
floating Only matches floating windows. This criterion requires no value.
floating\_from Like floating but this criterion takes two possible values: "auto" and "user". With "auto", only windows that were automatically opened as floating are matched. With "user", only windows that the user made floating are matched.
tiling Only matches tiling windows. This criterion requires no value.
tiling\_from Like tiling but this criterion takes two possible values: "auto" and "user". With "auto", only windows that were automatically opened as tiling are matched. With "user", only windows that the user made tiling are matched.
The criteria class, instance, role, title, workspace, machine and mark are actually regular expressions (PCRE). See pcresyntax(3) or perldoc perlre for information on how to use them.
### 6.1. Executing applications (exec)
What good is a window manager if you can’t actually start any applications? The exec command starts an application by passing the command you specify to a shell. This implies that you can use globbing (wildcards) and programs will be searched in your $PATH.
See [[command\_chaining]](#command_chaining) for details on the special meaning of ; (semicolon) and , (comma): they chain commands together in i3, so you need to use quoted strings (as shown in [[exec\_quoting]](#exec_quoting)) if they appear in your command.
**Syntax**:
```
exec [--no-startup-id] <command>
```
**Example**:
```
# Start the GIMP
bindsym $mod+g exec gimp
# Start the terminal emulator urxvt which is not yet startup-notification-aware
bindsym $mod+Return exec --no-startup-id urxvt
```
The --no-startup-id parameter disables startup-notification support for this particular exec command. With startup-notification, i3 can make sure that a window appears on the workspace on which you used the exec command. Also, it will change the X11 cursor to watch (a clock) while the application is launching. So, if an application is not startup-notification aware (most GTK and Qt using applications seem to be, though), you will end up with a watch cursor for 60 seconds.
If the command to be executed contains a ; (semicolon) and/or a , (comma), the entire command must be quoted. For example, to have a keybinding for the shell command notify-send Hello, i3, you would add an entry to your configuration file like this:
**Example**:
```
# Execute a command with a comma in it
bindsym $mod+p exec "notify-send Hello, i3"
```
If however a command with a comma and/or semicolon itself requires quotes, you must escape the internal quotation marks with double backslashes, like this:
**Example**:
```
# Execute a command with a comma, semicolon and internal quotes
bindsym $mod+p exec "notify-send \\"Hello, i3; from $USER\\""
```
### 6.2. Splitting containers
The split command makes the current window a split container. Split containers can contain multiple windows. Depending on the layout of the split container, new windows get placed to the right of the current one (splith) or new windows get placed below the current one (splitv).
If you apply this command to a split container with the same orientation, nothing will happen. If you use a different orientation, the split container’s orientation will be changed (if it does not have more than one window). The toggle option will toggle the orientation of the split container if it contains a single window. Otherwise it makes the current window a split container with opposite orientation compared to the parent container. Use layout toggle split to change the layout of any split container from splitv to splith or vice-versa. You can also define a custom sequence of layouts to cycle through with layout toggle, see [[manipulating\_layout]](#manipulating_layout).
**Syntax**:
```
split vertical|horizontal|toggle
```
**Example**:
```
bindsym $mod+v split vertical
bindsym $mod+h split horizontal
bindsym $mod+t split toggle
```
### 6.3. Manipulating layout
Use layout toggle split, layout stacking, layout tabbed, layout splitv or layout splith to change the current container layout to splith/splitv, stacking, tabbed layout, splitv or splith, respectively.
Specify up to four layouts after layout toggle to cycle through them. Every time the command is executed, the layout specified after the currently active one will be applied. If the currently active layout is not in the list, the first layout in the list will be activated.
To make the current window (!) fullscreen, use fullscreen enable (or fullscreen enable global for the global mode), to leave either fullscreen mode use fullscreen disable, and to toggle between these two states use fullscreen toggle (or fullscreen toggle global).
Likewise, to make the current window floating (or tiling again) use floating enable respectively floating disable (or floating toggle):
**Syntax**:
```
layout default|tabbed|stacking|splitv|splith
layout toggle [split|all]
layout toggle [split|tabbed|stacking|splitv|splith] [split|tabbed|stacking|splitv|splith]…
```
**Examples**:
```
bindsym $mod+s layout stacking
bindsym $mod+l layout toggle split
bindsym $mod+w layout tabbed
# Toggle between stacking/tabbed/split:
bindsym $mod+x layout toggle
# Toggle between stacking/tabbed/splith/splitv:
bindsym $mod+x layout toggle all
# Toggle between stacking/tabbed/splith:
bindsym $mod+x layout toggle stacking tabbed splith
# Toggle between splitv/tabbed
bindsym $mod+x layout toggle splitv tabbed
# Toggle between last split layout/tabbed/stacking
bindsym $mod+x layout toggle split tabbed stacking
# Toggle fullscreen
bindsym $mod+f fullscreen toggle
# Toggle floating/tiling
bindsym $mod+t floating toggle
```
### 6.4. Focusing containers
To change focus, you can use the focus command. The following options are available:
<criteria> Sets focus to the container that matches the specified criteria. See [[command\_criteria]](#command_criteria).
left|right|up|down Sets focus to the nearest container in the given direction.
parent Sets focus to the parent container of the current container.
child The opposite of focus parent, sets the focus to the last focused child container.
next|prev Automatically sets focus to the adjacent container. If sibling is specified, the command will focus the exact sibling container, including non-leaf containers like split containers. Otherwise, it is an automatic version of focus left|right|up|down in the orientation of the parent container.
floating Sets focus to the last focused floating container.
tiling Sets focus to the last focused tiling container.
mode\_toggle Toggles between floating/tiling containers.
output Followed by a direction or an output name, this will focus the corresponding output.
**Syntax**:
```
<criteria> focus
focus left|right|down|up
focus parent|child|floating|tiling|mode\_toggle
focus next|prev [sibling]
focus output left|right|down|up|current|primary|nonprimary|next|<output1> [output2]…
```
**Examples**:
```
# Focus firefox
bindsym $mod+F1 [class="Firefox"] focus
# Focus container on the left, bottom, top, right
bindsym $mod+j focus left
bindsym $mod+k focus down
bindsym $mod+l focus up
bindsym $mod+semicolon focus right
# Focus parent container
bindsym $mod+u focus parent
# Focus last floating/tiling container
bindsym $mod+g focus mode\_toggle
# Focus the next output (effectively toggles when you only have two outputs)
bindsym $mod+x move workspace to output next
# Focus the output right to the current one
bindsym $mod+x focus output right
# Focus the big output
bindsym $mod+x focus output HDMI-2
# Focus the primary output
bindsym $mod+x focus output primary
# Cycle focus through non-primary outputs
bindsym $mod+x focus output nonprimary
# Cycle focus between outputs VGA1 and LVDS1 but not DVI0
bindsym $mod+x move workspace to output VGA1 LVDS1
```
Note that you might not have a primary output configured yet. To do so, run:
```
xrandr --output <output> --primary
```
### 6.5. Moving containers
Use the move command to move a container.
**Syntax**:
```
# Moves the container into the given direction.
# The optional pixel argument specifies how far the
# container should be moved if it is floating and
# defaults to 10 pixels. The optional ppt argument
# means "percentage points", and if specified it indicates
# how many points the container should be moved if it is
# floating rather than by a pixel value.
move <left|right|down|up> [<amount> [px|ppt]]
# Moves the container to the specified pos\_x and pos\_y
# coordinates on the screen.
move position <pos\_x> [px|ppt] <pos\_y> [px|ppt]
# Moves the container to the center of the screen.
# If 'absolute' is used, it is moved to the center of
# all outputs.
move [absolute] position center
# Moves the container to the current position of the
# mouse cursor. Only affects floating containers.
move position mouse
```
**Examples**:
```
# Move container to the left, bottom, top, right
bindsym $mod+j move left
bindsym $mod+k move down
bindsym $mod+l move up
bindsym $mod+semicolon move right
# Move container, but make floating containers
# move more than the default
bindsym $mod+j move left 20 px
# Move floating container to the center of all outputs
bindsym $mod+c move absolute position center
# Move container to the current position of the cursor
bindsym $mod+m move position mouse
```
### 6.6. Swapping containers
Two containers can be swapped (i.e., move to each other’s position) by using the swap command. They will assume the position and geometry of the container they are swapped with.
The first container to participate in the swapping can be selected through the normal command criteria process with the focused window being the usual fallback if no criteria are specified. The second container can be selected using one of the following methods:
id The X11 window ID of a client window.
con\_id The i3 container ID of a container.
mark A container with the specified mark, see [[vim\_like\_marks]](#vim_like_marks).
Note that swapping does not work with all containers. Most notably, swapping containers that have a parent-child relationship to one another does not work.
**Syntax**:
```
swap container with id|con\_id|mark <arg>
```
**Examples**:
```
# Swaps the focused container with the container marked »swapee«.
swap container with mark swapee
# Swaps container marked »A« and »B«
[con\_mark="^A$"] swap container with mark B
```
### 6.7. Sticky floating windows
If you want a window to stick to the glass, i.e., have it stay on screen even if you switch to another workspace, you can use the sticky command. For example, this can be useful for notepads, a media player or a video chat window.
Note that while any window can be made sticky through this command, it will only take effect if the window is floating.
**Syntax**:
```
sticky enable|disable|toggle
```
**Examples**:
```
# make a terminal sticky that was started as a notepad
for\_window [instance=notepad] sticky enable
```
### 6.8. Changing (named) workspaces/moving to workspaces
To change to a specific workspace, use the workspace command, followed by the number or name of the workspace. Pass the optional flag --no-auto-back-and-forth to disable [[workspace\_auto\_back\_and\_forth]](#workspace_auto_back_and_forth) for this specific call only.
To move containers to specific workspaces, use move container to workspace.
You can also switch to the next and previous workspace with the commands workspace next and workspace prev, which is handy, for example, if you have workspace 1, 3, 4 and 9 and you want to cycle through them with a single key combination. To restrict those to the current output, use workspace next\_on\_output and workspace prev\_on\_output. Similarly, you can use move container to workspace next, move container to workspace prev to move a container to the next/previous workspace and move container to workspace current (the last one makes sense only when used with criteria).
workspace next cycles through either numbered or named workspaces. But when it reaches the last numbered/named workspace, it looks for named workspaces after exhausting numbered ones and looks for numbered ones after exhausting named ones.
See [[move\_to\_outputs]](#move_to_outputs) for how to move a container/workspace to a different RandR output.
Workspace names are parsed as [Pango markup](https://developer.gnome.org/pango/1.46/) by i3bar.
To switch back to the previously focused workspace, use workspace back\_and\_forth; likewise, you can move containers to the previously focused workspace using move container to workspace back\_and\_forth.
**Syntax**:
```
workspace next|prev|next\_on\_output|prev\_on\_output
workspace back\_and\_forth
workspace [--no-auto-back-and-forth] <name>
workspace [--no-auto-back-and-forth] number <name>
move [--no-auto-back-and-forth] [window|container] [to] workspace <name>
move [--no-auto-back-and-forth] [window|container] [to] workspace number <name>
move [window|container] [to] workspace prev|next|current
```
**Examples**:
```
bindsym $mod+1 workspace 1
bindsym $mod+2 workspace 2
bindsym $mod+3 workspace 3:<span foreground="red">vim</span>
...
bindsym $mod+Shift+1 move container to workspace 1
bindsym $mod+Shift+2 move container to workspace 2
...
# switch between the current and the previously focused one
bindsym $mod+b workspace back\_and\_forth
bindsym $mod+Shift+b move container to workspace back\_and\_forth
# move the whole workspace to the next output
bindsym $mod+x move workspace to output right
# move firefox to current workspace
bindsym $mod+F1 [class="Firefox"] move workspace current
```
#### 6.8.1. Named workspaces
Workspaces are identified by their name. So, instead of using numbers in the workspace command, you can use an arbitrary name:
**Example**:
```
bindsym $mod+1 workspace mail
...
```
If you want the workspace to have a number **and** a name, just prefix the number, like this:
**Example**:
```
bindsym $mod+1 workspace 1: mail
bindsym $mod+2 workspace 2: www
...
```
Note that the workspace will really be named "1: mail". i3 treats workspace names beginning with a number in a slightly special way. Normally, named workspaces are ordered the way they appeared. When they start with a number, i3 will order them numerically. Also, you will be able to use workspace number 1 to switch to the workspace which begins with number 1, regardless of which name it has. This is useful in case you are changing the workspace’s name dynamically. To combine both commands you can use workspace number 1: mail to specify a default name if there’s currently no workspace starting with a "1".
#### 6.8.2. Renaming workspaces
You can rename workspaces. This might be useful to start with the default numbered workspaces, do your work, and rename the workspaces afterwards to reflect what’s actually on them. You can also omit the old name to rename the currently focused workspace. This is handy if you want to use the rename command with i3-input.
**Syntax**:
```
rename workspace <old\_name> to <new\_name>
rename workspace to <new\_name>
```
**Examples**:
```
i3-msg 'rename workspace 5 to 6'
i3-msg 'rename workspace 1 to "1: www"'
i3-msg 'rename workspace "1: www" to "10: www"'
i3-msg 'rename workspace to "2: mail"'
bindsym $mod+r exec i3-input -F 'rename workspace to "%s"' -P 'New name: '
```
If you want to rename workspaces on demand while keeping the navigation stable, you can use a setup like this:
**Example**:
```
bindsym $mod+1 workspace number "1: www"
bindsym $mod+2 workspace number "2: mail"
...
```
If a workspace does not exist, the command workspace number "1: mail" will create workspace "1: mail".
If a workspace with number 1 already exists, the command will switch to this workspace and ignore the text part. So even when the workspace has been renamed "1: web", the above command will still switch to it. The command workspace 1 will however create and move to a new workspace "1" alongside the existing "1: mail" workspace.
### 6.9. Moving workspaces to a different screen
See [[move\_to\_outputs]](#move_to_outputs) for how to move a container/workspace to a different RandR output.
### 6.10. Moving containers/workspaces to RandR outputs
To move a container to another RandR output (addressed by names like LVDS1 or VGA1) or to a RandR output identified by a specific direction (like left, right, up or down), there are two commands:
**Syntax**:
```
move container to output left|right|down|up|current|primary|nonprimary|next|<output1> [output2]…
move workspace to output left|right|down|up|current|primary|nonprimary|next|<output1> [output2]…
```
**Examples**:
```
# Move the current workspace to the next output
# (effectively toggles when you only have two outputs)
bindsym $mod+x move workspace to output next
# Cycle this workspace between outputs VGA1 and LVDS1 but not DVI0
bindsym $mod+x move workspace to output VGA1 LVDS1
# Put this window on the presentation output.
bindsym $mod+x move container to output VGA1
# Put this window on the primary output.
bindsym $mod+x move container to output primary
```
If you specify more than one output, the container/workspace is cycled through them: If it is already in one of the outputs of the list, it will move to the next output in the list. If it is in an output not in the list, it will move to the first specified output. Non-existing outputs are skipped.
Note that you might not have a primary output configured yet. To do so, run:
```
xrandr --output <output> --primary
```
### 6.11. Moving containers/windows to marks
To move a container to another container with a specific mark (see [[vim\_like\_marks]](#vim_like_marks)), you can use the following command.
The window will be moved right after the marked container in the tree, i.e., it ends up in the same position as if you had opened a new window when the marked container was focused. If the mark is on a split container, the window will appear as a new child after the currently focused child within that container.
**Syntax**:
```
move window|container to mark <mark>
```
**Example**:
```
for\_window [instance="tabme"] move window to mark target
```
### 6.12. Resizing containers/windows
If you want to resize containers/windows using your keyboard, you can use the resize command:
**Syntax**:
```
resize grow|shrink <direction> [<px> px [or <ppt> ppt]]
resize set [width] <width> [px | ppt]
resize set height <height> [px | ppt]
resize set [width] <width> [px | ppt] [height] <height> [px | ppt]
```
Direction can either be one of up, down, left or right. Or you can be less specific and use width or height, in which case i3 will take/give space from all the other containers. The optional pixel argument specifies by how many pixels a container should be grown or shrunk (the default is 10 pixels). The optional ppt argument means "percentage points", and if specified it indicates that a **tiling container** should be grown or shrunk by that many points, instead of by the px value.
Note about resize set: a value of 0 for <width> or <height> means "do not resize in this direction".
It is recommended to define bindings for resizing in a dedicated binding mode. See [[binding\_modes]](#binding_modes) and the example in the i3 [default config](https://github.com/i3/i3/blob/next/etc/config.keycodes) for more context.
**Example**:
```
for\_window [class="urxvt"] resize set 640 480
```
### 6.13. Jumping to specific windows
Often when in a multi-monitor environment, you want to quickly jump to a specific window. For example, while working on workspace 3 you might want to jump to your mail client to email your boss that you’ve achieved some important goal. Instead of figuring out how to navigate to your mail client, it would be more convenient to have a shortcut. You can use the focus command with criteria for that.
**Syntax**:
```
[class="class"] focus
[title="title"] focus
```
**Examples**:
```
# Get me to the next open VIM instance
bindsym $mod+a [class="urxvt" title="VIM"] focus
```
### 6.14. VIM-like marks (mark/goto)
This feature is like the jump feature: It allows you to directly jump to a specific window (this means switching to the appropriate workspace and setting focus to the windows). However, you can directly mark a specific window with an arbitrary label and use it afterwards. You can unmark the label in the same way, using the unmark command. If you don’t specify a label, unmark removes all marks. You do not need to ensure that your windows have unique classes or titles, and you do not need to change your configuration file.
As the command needs to include the label with which you want to mark the window, you cannot simply bind it to a key. i3-input is a tool created for this purpose: It lets you input a command and sends the command to i3. It can also prefix this command and display a custom prompt for the input dialog.
The additional --toggle option will remove the mark if the window already has this mark or add it otherwise. Note that you might need to use this in combination with --add (see below) as any other marks will otherwise be removed.
The --replace flag causes i3 to remove any existing marks, which is also the default behavior. You can use the --add flag to put more than one mark on a window.
Refer to [[show\_marks]](#show_marks) if you don’t want marks to be shown in the window decoration.
**Syntax**:
```
mark [--add|--replace] [--toggle] <identifier>
[con\_mark="identifier"] focus
unmark <identifier>
```
You can use i3-input to prompt for a mark name, then use the mark and focus commands to create and jump to custom marks:
**Examples**:
```
# read 1 character and mark the current window with this character
bindsym $mod+m exec i3-input -F 'mark %s' -l 1 -P 'Mark: '
# read 1 character and go to the window with the character
bindsym $mod+g exec i3-input -F '[con\_mark="%s"] focus' -l 1 -P 'Goto: '
```
Alternatively, if you do not want to mess with i3-input, you could create separate bindings for a specific set of labels and then only use those labels:
**Example (in a terminal)**:
```
# marks the focused container
mark irssi
# focus the container with the mark "irssi"
'[con\_mark="irssi"] focus'
# remove the mark "irssi" from whichever container has it
unmark irssi
# remove all marks on all firefox windows
[class="(?i)firefox"] unmark
```
### 6.15. Window title format
By default, i3 will simply print the X11 window title. Using title\_format, this can be customized by setting the format to the desired output. This directive supports [Pango markup](https://developer.gnome.org/pango/1.46/) and the following placeholders which will be replaced:
%title For normal windows, this is the X11 window title (\_NET\_WM\_NAME or WM\_NAME as fallback). When used on containers without a window (e.g., a split container inside a tabbed/stacked layout), this will be the tree representation of the container (e.g., "H[xterm xterm]").
%class The X11 window class (second part of WM\_CLASS). This corresponds to the class criterion, see [[command\_criteria]](#command_criteria).
%instance The X11 window instance (first part of WM\_CLASS). This corresponds to the instance criterion, see [[command\_criteria]](#command_criteria).
%machine The X11 name of the machine (WM\_CLIENT\_MACHINE). This corresponds to the machine criterion, see [[command\_criteria]](#command_criteria).
Using the [[for\_window]](#for_window) directive, you can set the title format for any window based on [[command\_criteria]](#command_criteria).
**Syntax**:
```
title\_format <format>
```
**Examples**:
```
# give the focused window a prefix
bindsym $mod+p title\_format "Important | %title"
# print all window titles bold
for\_window [class=".\*"] title\_format "<b>%title</b>"
# print window titles of firefox windows red
for\_window [class="(?i)firefox"] title\_format "<span foreground='red'>%title</span>"
```
### 6.16. Window title icon
By default, i3 does not display the window icon in the title bar.
Starting with i3 v4.20, you can optionally enable window icons either for specific windows or for all windows (using the [[for\_window]](#for_window) directive).
**Syntax**:
```
title\_window\_icon <yes|no|toggle>
title\_window\_icon <padding|toggle> <px>
```
**Examples**:
```
# show the window icon for the focused window to make it stand out
bindsym $mod+p title\_window\_icon on
# enable window icons for all windows
for\_window [all] title\_window\_icon on
# enable window icons for all windows with extra horizontal padding
for\_window [all] title\_window\_icon padding 3px
```
### 6.17. Changing border style
To change the border of the current client, you can use border normal to use the normal border (including window title), border pixel 1 to use a 1-pixel border (no window title) and border none to make the client borderless.
There is also border toggle which will toggle the different border styles. The optional pixel argument can be used to specify the border width when switching to the normal and pixel styles.
Note that "pixel" refers to logical pixel. On HiDPI displays, a logical pixel is represented by multiple physical pixels, so pixel 1 might not necessarily translate into a single pixel row wide border.
**Syntax**:
```
border normal|pixel|toggle [<n>]
border none
# legacy syntax, equivalent to "border pixel 1"
border 1pixel
```
**Examples**:
```
# use window title, but no border
bindsym $mod+t border normal 0
# use no window title and a thick border
bindsym $mod+y border pixel 3
# use window title \*and\* a thick border
bindsym $mod+y border normal 3
# use neither window title nor border
bindsym $mod+u border none
# no border on VLC
for\_window [class="vlc"] border none
```
To change the default for all windows, see the directive [[default\_border]](#default_border).
### 6.18. Enabling shared memory logging
As described in <https://i3wm.org/docs/debugging.html>, i3 can log to a shared memory buffer, which you can dump using i3-dump-log. The shmlog command allows you to enable or disable the shared memory logging at runtime.
Note that when using shmlog <size\_in\_bytes>, the current log will be discarded and a new one will be started.
**Syntax**:
```
shmlog <size\_in\_bytes>
shmlog on|off|toggle
```
**Examples**:
```
# Enable/disable logging
bindsym $mod+x shmlog toggle
# or, from a terminal:
# increase the shared memory log buffer to 50 MiB
i3-msg shmlog $((50\*1024\*1024))
```
### 6.19. Enabling debug logging
The debuglog command allows you to enable or disable debug logging at runtime. Debug logging is much more verbose than non-debug logging. This command does not activate shared memory logging (shmlog), and as such is most likely useful in combination with the above-described [[shmlog]](#shmlog) command.
**Syntax**:
```
debuglog on|off|toggle
```
**Examples**:
```
# Enable/disable logging
bindsym $mod+x debuglog toggle
```
### 6.20. Reloading/Restarting/Exiting
You can make i3 reload its configuration file with reload. You can also restart i3 inplace with the restart command to get it out of some weird state (if that should ever happen) or to perform an upgrade without having to restart your X session. To exit i3 properly, you can use the exit command, however you don’t need to (simply killing your X session is fine as well).
**Examples**:
```
bindsym $mod+Shift+r restart
bindsym $mod+Shift+w reload
bindsym $mod+Shift+e exit
```
### 6.21. Scratchpad
There are two commands to use any existing window as scratchpad window. move scratchpad will move a window to the scratchpad workspace. This will make it invisible until you show it again. There is no way to open that workspace. Instead, when using scratchpad show, the window will be shown again, as a floating window, centered on your current workspace (using scratchpad show on a visible scratchpad window will make it hidden again, so you can have a keybinding to toggle). Note that this is just a normal floating window, so if you want to "remove it from scratchpad", you can simple make it tiling again (floating toggle).
As the name indicates, this is useful for having a window with your favorite editor always at hand. However, you can also use this for other permanently running applications which you don’t want to see all the time: Your music player, alsamixer, maybe even your mail client…?
**Syntax**:
```
move scratchpad
scratchpad show
```
**Examples**:
```
# Make the currently focused window a scratchpad
bindsym $mod+Shift+minus move scratchpad
# Show the first scratchpad window
bindsym $mod+minus scratchpad show
# Show the sup-mail scratchpad window, if any.
bindsym mod4+s [title="^Sup ::"] scratchpad show
```
### 6.22. Nop
There is a no operation command nop which allows you to override default behavior. This can be useful for, e.g., disabling a focus change on clicks with the middle mouse button.
The optional comment argument is ignored, but will be printed to the log file for debugging purposes.
**Syntax**:
```
nop [<comment>]
```
**Example**:
```
# Disable focus change for clicks on titlebars
# with the middle mouse button
bindsym button2 nop
```
### 6.23. i3bar control
There are two options in the configuration of each i3bar instance that can be changed during runtime by invoking a command through i3. The commands bar hidden\_state and bar mode allow setting the current hidden\_state respectively mode option of each bar. It is also possible to toggle between hide state and show state as well as between dock mode and hide mode. Each i3bar instance can be controlled individually by specifying a bar\_id, if none is given, the command is executed for all bar instances.
**Syntax**:
```
bar hidden\_state hide|show|toggle [<bar\_id>]
bar mode dock|hide|invisible|toggle [<bar\_id>]
```
**Examples**:
```
# Toggle between hide state and show state
bindsym $mod+m bar hidden\_state toggle
# Toggle between dock mode and hide mode
bindsym $mod+n bar mode toggle
# Set the bar instance with id 'bar-1' to switch to hide mode
bindsym $mod+b bar mode hide bar-1
# Set the bar instance with id 'bar-1' to always stay hidden
bindsym $mod+Shift+b bar mode invisible bar-1
```
### 6.24. Changing gaps
Gaps can be modified at runtime with the following command syntax:
**Syntax**:
```
# Inner gaps: space between two adjacent windows (or split containers).
gaps inner current|all set|plus|minus|toggle <gap\_size\_in\_px>
# Outer gaps: space along the screen edges.
gaps outer|horizontal|vertical|top|right|bottom|left current|all set|plus|minus|toggle <gap\_size\_in\_px>
```
With current or all you can change gaps either for only the currently focused or all currently existing workspaces (note that this does not affect the global configuration itself).
**Examples**:
```
gaps inner all set 20
gaps outer current plus 5
gaps horizontal current plus 40
gaps outer current toggle 60
for\_window [class="vlc"] gaps inner 0, gaps outer 0
```
To change the gaps for all windows, see the [[gaps]](#gaps) configuration directive.
7. Multiple monitors
--------------------
As you can see in the goal list on the website, i3 was specifically developed with support for multiple monitors in mind. This section will explain how to handle multiple monitors.
When you have only one monitor, things are simple. You usually start with workspace 1 on your monitor and open new ones as you need them.
When you have more than one monitor, each monitor will get an initial workspace. The first monitor gets 1, the second gets 2 and a possible third would get 3. When you switch to a workspace on a different monitor, i3 will switch to that monitor and then switch to the workspace. This way, you don’t need shortcuts to switch to a specific monitor, and you don’t need to remember where you put which workspace. New workspaces will be opened on the currently active monitor. It is not possible to have a monitor without a workspace.
The idea of making workspaces global is based on the observation that most users have a very limited set of workspaces on their additional monitors. They are often used for a specific task (browser, shell) or for monitoring several things (mail, IRC, syslog, …). Thus, using one workspace on one monitor and "the rest" on the other monitors often makes sense. However, as you can create an unlimited number of workspaces in i3 and tie them to specific screens, you can have the "traditional" approach of having X workspaces per screen by changing your configuration (using modes, for example).
### 7.1. Configuring your monitors
To help you get going if you have never used multiple monitors before, here is a short overview of the xrandr options which will probably be of interest to you. It is always useful to get an overview of the current screen configuration. Just run "xrandr" and you will get an output like the following:
```
$ xrandr
Screen 0: minimum 320 x 200, current 1280 x 800, maximum 8192 x 8192
VGA1 disconnected (normal left inverted right x axis y axis)
LVDS1 connected 1280x800+0+0 (normal left inverted right x axis y axis) 261mm x 163mm
1280x800 60.0\*+ 50.0
1024x768 85.0 75.0 70.1 60.0
832x624 74.6
800x600 85.1 72.2 75.0 60.3 56.2
640x480 85.0 72.8 75.0 59.9
720x400 85.0
640x400 85.1
640x350 85.1
```
Several things are important here: You can see that LVDS1 is connected (of course, it is the internal flat panel) but VGA1 is not. If you have a monitor connected to one of the ports but xrandr still says "disconnected", you should check your cable, monitor or graphics driver.
The maximum resolution you can see at the end of the first line is the maximum combined resolution of your monitors. By default, it is usually too low and has to be increased by editing /etc/X11/xorg.conf.
So, say you connected VGA1 and want to use it as an additional screen:
```
xrandr --output VGA1 --auto --left-of LVDS1
```
This command makes xrandr try to find the native resolution of the device connected to VGA1 and configures it to the left of your internal flat panel. When running "xrandr" again, the output looks like this:
```
$ xrandr
Screen 0: minimum 320 x 200, current 2560 x 1024, maximum 8192 x 8192
VGA1 connected 1280x1024+0+0 (normal left inverted right x axis y axis) 338mm x 270mm
1280x1024 60.0\*+ 75.0
1280x960 60.0
1152x864 75.0
1024x768 75.1 70.1 60.0
832x624 74.6
800x600 72.2 75.0 60.3 56.2
640x480 72.8 75.0 66.7 60.0
720x400 70.1
LVDS1 connected 1280x800+1280+0 (normal left inverted right x axis y axis) 261mm x 163mm
1280x800 60.0\*+ 50.0
1024x768 85.0 75.0 70.1 60.0
832x624 74.6
800x600 85.1 72.2 75.0 60.3 56.2
640x480 85.0 72.8 75.0 59.9
720x400 85.0
640x400 85.1
640x350 85.1
```
Please note that i3 uses exactly the same API as xrandr does, so it will see only what you can see in xrandr.
See also [[presentations]](#presentations) for more examples of multi-monitor setups.
### 7.2. Interesting configuration for multi-monitor environments
There are several things to configure in i3 which might be interesting if you have more than one monitor:
1. You can specify which workspace should be put on which screen. This allows you to have a different set of workspaces when starting than just 1 for the first monitor, 2 for the second and so on. See [[workspace\_screen]](#workspace_screen).
2. If you want some applications to generally open on the bigger screen (MPlayer, Firefox, …), you can assign them to a specific workspace, see [[assign\_workspace]](#assign_workspace).
3. If you have many workspaces on many monitors, it might get hard to keep track of which window you put where. Thus, you can use vim-like marks to quickly switch between windows. See [[vim\_like\_marks]](#vim_like_marks).
4. For information on how to move existing workspaces between monitors, see [[move\_to\_outputs]](#move_to_outputs).
8. i3 and the rest of your software world
-----------------------------------------
### 8.1. Displaying a status line
A very common thing amongst users of exotic window managers is a status line at some corner of the screen. It is an often superior replacement to the widget approach you have in the task bar of a traditional desktop environment.
If you don’t already have your favorite way of generating such a status line (self-written scripts, conky, …), then i3status is the recommended tool for this task. It was written in C with the goal of using as few syscalls as possible to reduce the time your CPU is woken up from sleep states. Because i3status only spits out text, you need to combine it with some other tool, like i3bar. See [[status\_command]](#status_command) for how to display i3status in i3bar.
Regardless of which application you use to display the status line, you want to make sure that it registers as a dock window using EWMH hints. i3 will position the window either at the top or at the bottom of the screen, depending on which hint the application sets. With i3bar, you can configure its position, see [[i3bar\_position]](#i3bar_position).
### 8.2. Giving presentations (multi-monitor)
When giving a presentation, you typically want the audience to see what you see on your screen and then go through a series of slides (if the presentation is simple). For more complex presentations, you might want to have some notes which only you can see on your screen, while the audience can only see the slides.
#### 8.2.1. Case 1: everybody gets the same output
This is the simple case. You connect your computer to the video projector, turn on both (computer and video projector) and configure your X server to clone the internal flat panel of your computer to the video output:
```
xrandr --output VGA1 --mode 1024x768 --same-as LVDS1
```
i3 will then use the lowest common subset of screen resolutions, the rest of your screen will be left untouched (it will show the X background). So, in our example, this would be 1024x768 (my notebook has 1280x800).
#### 8.2.2. Case 2: you can see more than your audience
This case is a bit harder. First of all, you should configure the VGA output somewhere near your internal flat panel, say right of it:
```
xrandr --output VGA1 --mode 1024x768 --right-of LVDS1
```
Now, i3 will put a new workspace (depending on your settings) on the new screen and you are in multi-monitor mode (see [[multi\_monitor]](#multi_monitor)).
Because i3 is not a compositing window manager, there is no ability to display a window on two screens at the same time. Instead, your presentation software needs to do this job (that is, open a window on each screen).
### 8.3. High-resolution displays (aka HIDPI displays)
See <https://wiki.archlinux.org/index.php/HiDPI> for details on how to enable scaling in various parts of the Linux desktop. i3 will read the desired DPI from the Xft.dpi property. The property defaults to 96 DPI, so to achieve 200% scaling, you’d set Xft.dpi: 192 in ~/.Xresources.
If you are a long-time i3 user who just got a new monitor, double-check that:
* You are using a scalable font (starting with “pango:”) in your i3 config.
* You are using a terminal emulator which supports scaling. You could temporarily switch to gnome-terminal, which is known to support scaling out of the box, until you figure out how to adjust the font size in your favorite terminal emulator.
| programming_docs |
cmake CMake Reference Documentation CMake Reference Documentation
=============================
Command-Line Tools
------------------
* [cmake(1)](manual/cmake.1)
* [ctest(1)](manual/ctest.1)
* [cpack(1)](manual/cpack.1)
Interactive Dialogs
-------------------
* [cmake-gui(1)](manual/cmake-gui.1)
* [ccmake(1)](manual/ccmake.1)
Reference Manuals
-----------------
* [cmake-buildsystem(7)](manual/cmake-buildsystem.7)
* [cmake-commands(7)](manual/cmake-commands.7)
* [cmake-compile-features(7)](manual/cmake-compile-features.7)
* [cmake-developer(7)](manual/cmake-developer.7)
* [cmake-generator-expressions(7)](manual/cmake-generator-expressions.7)
* [cmake-generators(7)](manual/cmake-generators.7)
* [cmake-language(7)](manual/cmake-language.7)
* [cmake-server(7)](manual/cmake-server.7)
* [cmake-modules(7)](manual/cmake-modules.7)
* [cmake-packages(7)](manual/cmake-packages.7)
* [cmake-policies(7)](manual/cmake-policies.7)
* [cmake-properties(7)](manual/cmake-properties.7)
* [cmake-qt(7)](manual/cmake-qt.7)
* [cmake-toolchains(7)](manual/cmake-toolchains.7)
* [cmake-variables(7)](manual/cmake-variables.7)
cmake DISABLED DISABLED
========
If set to true, the test will be skipped and its status will be ‘Not Run’. A DISABLED test will not be counted in the total number of tests and its completion status will be reported to CDash as ‘Disabled’.
A DISABLED test does not participate in test fixture dependency resolution. If a DISABLED test has fixture requirements defined in its [`FIXTURES_REQUIRED`](fixtures_required#prop_test:FIXTURES_REQUIRED "FIXTURES_REQUIRED") property, it will not cause setup or cleanup tests for those fixtures to be added to the test set.
If a test with the [`FIXTURES_SETUP`](fixtures_setup#prop_test:FIXTURES_SETUP "FIXTURES_SETUP") property set is DISABLED, the fixture behavior will be as though that setup test was passing and any test case requiring that fixture will still run.
cmake ENVIRONMENT ENVIRONMENT
===========
Specify environment variables that should be defined for running a test.
If set to a list of environment variables and values of the form MYVAR=value those environment variables will be defined while running the test. The environment is restored to its previous state after the test is done.
cmake FIXTURES_SETUP FIXTURES\_SETUP
===============
Specifies a list of fixtures for which the test is to be treated as a setup test.
Fixture setup tests are ordinary tests with all of the usual test functionality. Setting the `FIXTURES_SETUP` property for a test has two primary effects:
* CTest will ensure the test executes before any other test which lists the fixture(s) in its [`FIXTURES_REQUIRED`](fixtures_required#prop_test:FIXTURES_REQUIRED "FIXTURES_REQUIRED") property.
* If CTest is asked to run only a subset of tests (e.g. using regular expressions or the `--rerun-failed` option) and the setup test is not in the set of tests to run, it will automatically be added if any tests in the set require any fixture listed in `FIXTURES_SETUP`.
A setup test can have multiple fixtures listed in its `FIXTURES_SETUP` property. It will execute only once for the whole CTest run, not once for each fixture. A fixture can also have more than one setup test defined. If there are multiple setup tests for a fixture, projects can control their order with the usual [`DEPENDS`](depends#prop_test:DEPENDS "DEPENDS") test property if necessary.
A setup test is allowed to require other fixtures, but not any fixture listed in its `FIXTURES_SETUP` property. For example:
```
# Ok: dependent fixture is different to setup
set_tests_properties(setupFoo PROPERTIES
FIXTURES_SETUP Foo
FIXTURES_REQUIRED Bar
)
# Error: cannot require same fixture as setup
set_tests_properties(setupFoo PROPERTIES
FIXTURES_SETUP Foo
FIXTURES_REQUIRED Foo
)
```
If any of a fixture’s setup tests fail, none of the tests listing that fixture in its [`FIXTURES_REQUIRED`](fixtures_required#prop_test:FIXTURES_REQUIRED "FIXTURES_REQUIRED") property will be run. Cleanup tests will, however, still be executed.
See [`FIXTURES_REQUIRED`](fixtures_required#prop_test:FIXTURES_REQUIRED "FIXTURES_REQUIRED") for a more complete discussion of how to use test fixtures.
cmake REQUIRED_FILES REQUIRED\_FILES
===============
List of files required to run the test.
If set to a list of files, the test will not be run unless all of the files exist.
cmake ATTACHED_FILES_ON_FAIL ATTACHED\_FILES\_ON\_FAIL
=========================
Attach a list of files to a dashboard submission if the test fails.
Same as [`ATTACHED_FILES`](attached_files#prop_test:ATTACHED_FILES "ATTACHED_FILES"), but these files will only be included if the test does not pass.
cmake TIMEOUT_AFTER_MATCH TIMEOUT\_AFTER\_MATCH
=====================
Change a test’s timeout duration after a matching line is encountered in its output.
Usage
-----
```
add_test(mytest ...)
set_property(TEST mytest PROPERTY TIMEOUT_AFTER_MATCH "${seconds}" "${regex}")
```
Description
-----------
Allow a test `seconds` to complete after `regex` is encountered in its output.
When the test outputs a line that matches `regex` its start time is reset to the current time and its timeout duration is changed to `seconds`. Prior to this, the timeout duration is determined by the [`TIMEOUT`](timeout#prop_test:TIMEOUT "TIMEOUT") property or the [`CTEST_TEST_TIMEOUT`](../variable/ctest_test_timeout#variable:CTEST_TEST_TIMEOUT "CTEST_TEST_TIMEOUT") variable if either of these are set. Because the test’s start time is reset, its execution time will not include any time that was spent waiting for the matching output.
[`TIMEOUT_AFTER_MATCH`](#prop_test:TIMEOUT_AFTER_MATCH "TIMEOUT_AFTER_MATCH") is useful for avoiding spurious timeouts when your test must wait for some system resource to become available before it can execute. Set [`TIMEOUT`](timeout#prop_test:TIMEOUT "TIMEOUT") to a longer duration that accounts for resource acquisition and use [`TIMEOUT_AFTER_MATCH`](#prop_test:TIMEOUT_AFTER_MATCH "TIMEOUT_AFTER_MATCH") to control how long the actual test is allowed to run.
If the required resource can be controlled by CTest you should use [`RESOURCE_LOCK`](resource_lock#prop_test:RESOURCE_LOCK "RESOURCE_LOCK") instead of [`TIMEOUT_AFTER_MATCH`](#prop_test:TIMEOUT_AFTER_MATCH "TIMEOUT_AFTER_MATCH"). This property should be used when only the test itself can determine when its required resources are available.
cmake ATTACHED_FILES ATTACHED\_FILES
===============
Attach a list of files to a dashboard submission.
Set this property to a list of files that will be encoded and submitted to the dashboard as an addition to the test result.
cmake DEPENDS DEPENDS
=======
Specifies that this test should only be run after the specified list of tests.
Set this to a list of tests that must finish before this test is run. The results of those tests are not considered, the dependency relationship is purely for order of execution (i.e. it is really just a *run after* relationship). Consider using test fixtures with setup tests if a dependency with successful completion is required (see [`FIXTURES_REQUIRED`](fixtures_required#prop_test:FIXTURES_REQUIRED "FIXTURES_REQUIRED")).
cmake TIMEOUT TIMEOUT
=======
How many seconds to allow for this test.
This property if set will limit a test to not take more than the specified number of seconds to run. If it exceeds that the test process will be killed and ctest will move to the next test. This setting takes precedence over [`CTEST_TEST_TIMEOUT`](../variable/ctest_test_timeout#variable:CTEST_TEST_TIMEOUT "CTEST_TEST_TIMEOUT").
cmake RUN_SERIAL RUN\_SERIAL
===========
Do not run this test in parallel with any other test.
Use this option in conjunction with the ctest\_test PARALLEL\_LEVEL option to specify that this test should not be run in parallel with any other tests.
cmake FIXTURES_CLEANUP FIXTURES\_CLEANUP
=================
Specifies a list of fixtures for which the test is to be treated as a cleanup test.
Fixture cleanup tests are ordinary tests with all of the usual test functionality. Setting the `FIXTURES_CLEANUP` property for a test has two primary effects:
* CTest will ensure the test executes after all other tests which list any of the fixtures in its [`FIXTURES_REQUIRED`](fixtures_required#prop_test:FIXTURES_REQUIRED "FIXTURES_REQUIRED") property.
* If CTest is asked to run only a subset of tests (e.g. using regular expressions or the `--rerun-failed` option) and the cleanup test is not in the set of tests to run, it will automatically be added if any tests in the set require any fixture listed in `FIXTURES_CLEANUP`.
A cleanup test can have multiple fixtures listed in its `FIXTURES_CLEANUP` property. It will execute only once for the whole CTest run, not once for each fixture. A fixture can also have more than one cleanup test defined. If there are multiple cleanup tests for a fixture, projects can control their order with the usual [`DEPENDS`](depends#prop_test:DEPENDS "DEPENDS") test property if necessary.
A cleanup test is allowed to require other fixtures, but not any fixture listed in its `FIXTURES_CLEANUP` property. For example:
```
# Ok: Dependent fixture is different to cleanup
set_tests_properties(cleanupFoo PROPERTIES
FIXTURES_CLEANUP Foo
FIXTURES_REQUIRED Bar
)
# Error: cannot require same fixture as cleanup
set_tests_properties(cleanupFoo PROPERTIES
FIXTURES_CLEANUP Foo
FIXTURES_REQUIRED Foo
)
```
Cleanup tests will execute even if setup or regular tests for that fixture fail or are skipped.
See [`FIXTURES_REQUIRED`](fixtures_required#prop_test:FIXTURES_REQUIRED "FIXTURES_REQUIRED") for a more complete discussion of how to use test fixtures.
cmake MEASUREMENT MEASUREMENT
===========
Specify a CDASH measurement and value to be reported for a test.
If set to a name then that name will be reported to CDASH as a named measurement with a value of 1. You may also specify a value by setting MEASUREMENT to “measurement=value”.
cmake COST COST
====
Set this to a floating point value. Tests in a test set will be run in descending order of cost.
This property describes the cost of a test. You can explicitly set this value; tests with higher COST values will run first.
cmake PROCESSORS PROCESSORS
==========
How many process slots this test requires
Denotes the number of processors that this test will require. This is typically used for MPI tests, and should be used in conjunction with the ctest\_test PARALLEL\_LEVEL option.
cmake WILL_FAIL WILL\_FAIL
==========
If set to true, this will invert the pass/fail flag of the test.
This property can be used for tests that are expected to fail and return a non zero return code.
cmake FAIL_REGULAR_EXPRESSION FAIL\_REGULAR\_EXPRESSION
=========================
If the output matches this regular expression the test will fail.
If set, if the output matches one of specified regular expressions, the test will fail. Example:
```
set_tests_properties(mytest PROPERTIES
FAIL_REGULAR_EXPRESSION "[^a-z]Error;ERROR;Failed"
)
```
`FAIL_REGULAR_EXPRESSION` expects a list of regular expressions.
cmake FIXTURES_REQUIRED FIXTURES\_REQUIRED
==================
Specifies a list of fixtures the test requires. Fixture names are case sensitive.
Fixtures are a way to attach setup and cleanup tasks to a set of tests. If a test requires a given fixture, then all tests marked as setup tasks for that fixture will be executed first (once for the whole set of tests, not once per test requiring the fixture). After all tests requiring a particular fixture have completed, CTest will ensure all tests marked as cleanup tasks for that fixture are then executed. Tests are marked as setup tasks with the [`FIXTURES_SETUP`](fixtures_setup#prop_test:FIXTURES_SETUP "FIXTURES_SETUP") property and as cleanup tasks with the [`FIXTURES_CLEANUP`](fixtures_cleanup#prop_test:FIXTURES_CLEANUP "FIXTURES_CLEANUP") property. If any of a fixture’s setup tests fail, all tests listing that fixture in their `FIXTURES_REQUIRED` property will not be executed. The cleanup tests for the fixture will always be executed, even if some setup tests fail.
When CTest is asked to execute only a subset of tests (e.g. by the use of regular expressions or when run with the `--rerun-failed` command line option), it will automatically add any setup or cleanup tests for fixtures required by any of the tests that are in the execution set.
Since setup and cleanup tasks are also tests, they can have an ordering specified by the [`DEPENDS`](depends#prop_test:DEPENDS "DEPENDS") test property just like any other tests. This can be exploited to implement setup or cleanup using multiple tests for a single fixture to modularise setup or cleanup logic.
The concept of a fixture is different to that of a resource specified by [`RESOURCE_LOCK`](resource_lock#prop_test:RESOURCE_LOCK "RESOURCE_LOCK"), but they may be used together. A fixture defines a set of tests which share setup and cleanup requirements, whereas a resource lock has the effect of ensuring a particular set of tests do not run in parallel. Some situations may need both, such as setting up a database, serialising test access to that database and deleting the database again at the end. For such cases, tests would populate both `FIXTURES_REQUIRED` and [`RESOURCE_LOCK`](resource_lock#prop_test:RESOURCE_LOCK "RESOURCE_LOCK") to combine the two behaviours. Names used for [`RESOURCE_LOCK`](resource_lock#prop_test:RESOURCE_LOCK "RESOURCE_LOCK") have no relationship with names of fixtures, so note that a resource lock does not imply a fixture and vice versa.
Consider the following example which represents a database test scenario similar to that mentioned above:
```
add_test(NAME testsDone COMMAND emailResults)
add_test(NAME fooOnly COMMAND testFoo)
add_test(NAME dbOnly COMMAND testDb)
add_test(NAME dbWithFoo COMMAND testDbWithFoo)
add_test(NAME createDB COMMAND initDB)
add_test(NAME setupUsers COMMAND userCreation)
add_test(NAME cleanupDB COMMAND deleteDB)
add_test(NAME cleanupFoo COMMAND removeFoos)
set_tests_properties(setupUsers PROPERTIES DEPENDS createDB)
set_tests_properties(createDB PROPERTIES FIXTURES_SETUP DB)
set_tests_properties(setupUsers PROPERTIES FIXTURES_SETUP DB)
set_tests_properties(cleanupDB PROPERTIES FIXTURES_CLEANUP DB)
set_tests_properties(cleanupFoo PROPERTIES FIXTURES_CLEANUP Foo)
set_tests_properties(testsDone PROPERTIES FIXTURES_CLEANUP "DB;Foo")
set_tests_properties(fooOnly PROPERTIES FIXTURES_REQUIRED Foo)
set_tests_properties(dbOnly PROPERTIES FIXTURES_REQUIRED DB)
set_tests_properties(dbWithFoo PROPERTIES FIXTURES_REQUIRED "DB;Foo")
set_tests_properties(dbOnly dbWithFoo createDB setupUsers cleanupDB
PROPERTIES RESOURCE_LOCK DbAccess)
```
Key points from this example:
* Two fixtures are defined: `DB` and `Foo`. Tests can require a single fixture as `fooOnly` and `dbOnly` do, or they can depend on multiple fixtures like `dbWithFoo` does.
* A `DEPENDS` relationship is set up to ensure `setupUsers` happens after `createDB`, both of which are setup tests for the `DB` fixture and will therefore be executed before the `dbOnly` and `dbWithFoo` tests automatically.
* No explicit `DEPENDS` relationships were needed to make the setup tests run before or the cleanup tests run after the regular tests.
* The `Foo` fixture has no setup tests defined, only a single cleanup test.
* `testsDone` is a cleanup test for both the `DB` and `Foo` fixtures. Therefore, it will only execute once regular tests for both fixtures have finished (i.e. after `fooOnly`, `dbOnly` and `dbWithFoo`). No `DEPENDS` relationship was specified for `testsDone`, so it is free to run before, after or concurrently with other cleanup tests for either fixture.
* The setup and cleanup tests never list the fixtures they are for in their own `FIXTURES_REQUIRED` property, as that would result in a dependency on themselves and be considered an error.
cmake PASS_REGULAR_EXPRESSION PASS\_REGULAR\_EXPRESSION
=========================
The output must match this regular expression for the test to pass.
If set, the test output will be checked against the specified regular expressions and at least one of the regular expressions has to match, otherwise the test will fail. Example:
```
set_tests_properties(mytest PROPERTIES
PASS_REGULAR_EXPRESSION "TestPassed;All ok"
)
```
`PASS_REGULAR_EXPRESSION` expects a list of regular expressions.
cmake WORKING_DIRECTORY WORKING\_DIRECTORY
==================
The directory from which the test executable will be called.
If this is not set it is called from the directory the test executable is located in.
cmake LABELS LABELS
======
Specify a list of text labels associated with a test.
The list is reported in dashboard submissions.
cmake SKIP_RETURN_CODE SKIP\_RETURN\_CODE
==================
Return code to mark a test as skipped.
Sometimes only a test itself can determine if all requirements for the test are met. If such a situation should not be considered a hard failure a return code of the process can be specified that will mark the test as “Not Run” if it is encountered.
cmake RESOURCE_LOCK RESOURCE\_LOCK
==============
Specify a list of resources that are locked by this test.
If multiple tests specify the same resource lock, they are guaranteed not to run concurrently.
See also [`FIXTURES_REQUIRED`](fixtures_required#prop_test:FIXTURES_REQUIRED "FIXTURES_REQUIRED") if the resource requires any setup or cleanup steps.
cmake CMAKE_CXX_STANDARD_REQUIRED CMAKE\_CXX\_STANDARD\_REQUIRED
==============================
Default value for [`CXX_STANDARD_REQUIRED`](../prop_tgt/cxx_standard_required#prop_tgt:CXX_STANDARD_REQUIRED "CXX_STANDARD_REQUIRED") property of targets.
This variable is used to initialize the [`CXX_STANDARD_REQUIRED`](../prop_tgt/cxx_standard_required#prop_tgt:CXX_STANDARD_REQUIRED "CXX_STANDARD_REQUIRED") property on all targets. See that target property for additional information.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
cmake CMAKE_<LANG>_IMPLICIT_LINK_DIRECTORIES CMAKE\_<LANG>\_IMPLICIT\_LINK\_DIRECTORIES
==========================================
Implicit linker search path detected for language `<LANG>`.
Compilers typically pass directories containing language runtime libraries and default library search paths when they invoke a linker. These paths are implicit linker search directories for the compiler’s language. CMake automatically detects these directories for each language and reports the results in this variable.
When a library in one of these directories is given by full path to [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") CMake will generate the `-l<name>` form on link lines to ensure the linker searches its implicit directories for the library. Note that some toolchains read implicit directories from an environment variable such as `LIBRARY_PATH` so keep its value consistent when operating in a given build tree.
cmake CTEST_CUSTOM_PRE_TEST CTEST\_CUSTOM\_PRE\_TEST
========================
A list of commands to run at the start of the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CTEST_BZR_COMMAND CTEST\_BZR\_COMMAND
===================
Specify the CTest `BZRCommand` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
| programming_docs |
cmake CMAKE_CUDA_STANDARD CMAKE\_CUDA\_STANDARD
=====================
Default value for [`CUDA_STANDARD`](../prop_tgt/cuda_standard#prop_tgt:CUDA_STANDARD "CUDA_STANDARD") property of targets.
This variable is used to initialize the [`CUDA_STANDARD`](../prop_tgt/cuda_standard#prop_tgt:CUDA_STANDARD "CUDA_STANDARD") property on all targets. See that target property for additional information.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
cmake CMAKE_<LANG>_SOURCE_FILE_EXTENSIONS CMAKE\_<LANG>\_SOURCE\_FILE\_EXTENSIONS
=======================================
Extensions of source files for the given language.
This is the list of extensions for a given language’s source files.
cmake CMAKE_EXPORT_COMPILE_COMMANDS CMAKE\_EXPORT\_COMPILE\_COMMANDS
================================
Enable/Disable output of compile commands during generation.
If enabled, generates a `compile_commands.json` file containing the exact compiler calls for all translation units of the project in machine-readable form. The format of the JSON file looks like:
```
[
{
"directory": "/home/user/development/project",
"command": "/usr/bin/c++ ... -c ../foo/foo.cc",
"file": "../foo/foo.cc"
},
...
{
"directory": "/home/user/development/project",
"command": "/usr/bin/c++ ... -c ../foo/bar.cc",
"file": "../foo/bar.cc"
}
]
```
Note
This option is implemented only by [Makefile Generators](../manual/cmake-generators.7#makefile-generators) and the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja"). It is ignored on other generators.
cmake CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE CMAKE\_PROJECT\_<PROJECT-NAME>\_INCLUDE
=======================================
A CMake language file or module to be included by the [`project()`](../command/project#command:project "project") command. This is is intended for injecting custom code into project builds without modifying their source.
cmake CMAKE_COMPILER_IS_GNUG77 CMAKE\_COMPILER\_IS\_GNUG77
===========================
True if the `Fortran` compiler is GNU. Use [`CMAKE_Fortran_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") instead.
cmake CMAKE_CURRENT_LIST_DIR CMAKE\_CURRENT\_LIST\_DIR
=========================
Full directory of the listfile currently being processed.
As CMake processes the listfiles in your project this variable will always be set to the directory where the listfile which is currently being processed ([`CMAKE_CURRENT_LIST_FILE`](cmake_current_list_file#variable:CMAKE_CURRENT_LIST_FILE "CMAKE_CURRENT_LIST_FILE")) is located. The value has dynamic scope. When CMake starts processing commands in a source file it sets this variable to the directory where this file is located. When CMake finishes processing commands from the file it restores the previous value. Therefore the value of the variable inside a macro or function is the directory of the file invoking the bottom-most entry on the call stack, not the directory of the file containing the macro or function definition.
See also [`CMAKE_CURRENT_LIST_FILE`](cmake_current_list_file#variable:CMAKE_CURRENT_LIST_FILE "CMAKE_CURRENT_LIST_FILE").
cmake CMAKE_SIZEOF_VOID_P CMAKE\_SIZEOF\_VOID\_P
======================
Size of a `void` pointer.
This is set to the size of a pointer on the target machine, and is determined by a try compile. If a 64-bit size is found, then the library search path is modified to look for 64-bit libraries first.
cmake CMAKE_AUTOUIC CMAKE\_AUTOUIC
==============
Whether to handle `uic` automatically for Qt targets.
This variable is used to initialize the [`AUTOUIC`](../prop_tgt/autouic#prop_tgt:AUTOUIC "AUTOUIC") property on all the targets. See that target property for additional information.
cmake CMAKE_MAJOR_VERSION CMAKE\_MAJOR\_VERSION
=====================
First version number component of the [`CMAKE_VERSION`](cmake_version#variable:CMAKE_VERSION "CMAKE_VERSION") variable.
cmake CMAKE_INTERPROCEDURAL_OPTIMIZATION CMAKE\_INTERPROCEDURAL\_OPTIMIZATION
====================================
Default value for [`INTERPROCEDURAL_OPTIMIZATION`](../prop_tgt/interprocedural_optimization#prop_tgt:INTERPROCEDURAL_OPTIMIZATION "INTERPROCEDURAL_OPTIMIZATION") of targets.
This variable is used to initialize the [`INTERPROCEDURAL_OPTIMIZATION`](../prop_tgt/interprocedural_optimization#prop_tgt:INTERPROCEDURAL_OPTIMIZATION "INTERPROCEDURAL_OPTIMIZATION") property on all the targets. See that target property for additional information.
cmake CMAKE_ARCHIVE_OUTPUT_DIRECTORY_<CONFIG> CMAKE\_ARCHIVE\_OUTPUT\_DIRECTORY\_<CONFIG>
===========================================
Where to put all the [ARCHIVE](../manual/cmake-buildsystem.7#archive-output-artifacts) target files when built for a specific configuration.
This variable is used to initialize the [`ARCHIVE_OUTPUT_DIRECTORY_<CONFIG>`](# "ARCHIVE_OUTPUT_DIRECTORY_<CONFIG>") property on all the targets. See that target property for additional information.
cmake CMAKE_FIND_FRAMEWORK CMAKE\_FIND\_FRAMEWORK
======================
This variable affects how `find_*` commands choose between OS X Frameworks and unix-style package components.
On Darwin or systems supporting OS X Frameworks, the `CMAKE_FIND_FRAMEWORK` variable can be set to empty or one of the following:
`FIRST` Try to find frameworks before standard libraries or headers. This is the default on Darwin.
`LAST` Try to find frameworks after standard libraries or headers.
`ONLY` Only try to find frameworks.
`NEVER` Never try to find frameworks.
cmake CTEST_CONFIGURE_COMMAND CTEST\_CONFIGURE\_COMMAND
=========================
Specify the CTest `ConfigureCommand` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_<LANG>_CREATE_SHARED_LIBRARY CMAKE\_<LANG>\_CREATE\_SHARED\_LIBRARY
======================================
Rule variable to create a shared library.
This is a rule variable that tells CMake how to create a shared library for the language `<LANG>`.
cmake CMAKE_INTERPROCEDURAL_OPTIMIZATION_<CONFIG> CMAKE\_INTERPROCEDURAL\_OPTIMIZATION\_<CONFIG>
==============================================
Default value for [`INTERPROCEDURAL_OPTIMIZATION_<CONFIG>`](# "INTERPROCEDURAL_OPTIMIZATION_<CONFIG>") of targets.
This variable is used to initialize the [`INTERPROCEDURAL_OPTIMIZATION_<CONFIG>`](# "INTERPROCEDURAL_OPTIMIZATION_<CONFIG>") property on all the targets. See that target property for additional information.
cmake MSVC_VERSION MSVC\_VERSION
=============
The version of Microsoft Visual C/C++ being used if any.
Known version numbers are:
```
1200 = VS 6.0
1300 = VS 7.0
1310 = VS 7.1
1400 = VS 8.0
1500 = VS 9.0
1600 = VS 10.0
1700 = VS 11.0
1800 = VS 12.0
1900 = VS 14.0
1910 = VS 15.0
```
cmake CMAKE_<LANG>_COMPILER_AR CMAKE\_<LANG>\_COMPILER\_AR
===========================
A wrapper around `ar` adding the appropriate `--plugin` option for the compiler.
See also [`CMAKE_AR`](cmake_ar#variable:CMAKE_AR "CMAKE_AR").
cmake CMAKE_LIBRARY_PATH_FLAG CMAKE\_LIBRARY\_PATH\_FLAG
==========================
The flag to be used to add a library search path to a compiler.
The flag will be used to specify a library directory to the compiler. On most compilers this is `-L`.
cmake CMAKE_VS_MSBUILD_COMMAND CMAKE\_VS\_MSBUILD\_COMMAND
===========================
The generators for [`Visual Studio 10 2010`](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%2010%202010.html#generator:Visual%20Studio%2010%202010 "Visual Studio 10 2010") and above set this variable to the `MSBuild.exe` command installed with the corresponding Visual Studio version.
This variable is not defined by other generators even if `MSBuild.exe` is installed on the computer.
The [`CMAKE_VS_DEVENV_COMMAND`](cmake_vs_devenv_command#variable:CMAKE_VS_DEVENV_COMMAND "CMAKE_VS_DEVENV_COMMAND") is also provided for the non-Express editions of Visual Studio. See also the [`CMAKE_MAKE_PROGRAM`](cmake_make_program#variable:CMAKE_MAKE_PROGRAM "CMAKE_MAKE_PROGRAM") variable.
cmake CMAKE_ANDROID_NDK CMAKE\_ANDROID\_NDK
===================
When [Cross Compiling for Android with the NDK](../manual/cmake-toolchains.7#cross-compiling-for-android-with-the-ndk), this variable holds the absolute path to the root directory of the NDK. The directory must contain a `platforms` subdirectory holding the `android-<api>` directories.
cmake CMAKE_LINK_SEARCH_START_STATIC CMAKE\_LINK\_SEARCH\_START\_STATIC
==================================
Assume the linker looks for static libraries by default.
Some linkers support switches such as `-Bstatic` and `-Bdynamic` to determine whether to use static or shared libraries for `-lXXX` options. CMake uses these options to set the link type for libraries whose full paths are not known or (in some cases) are in implicit link directories for the platform. By default the linker search type is assumed to be `-Bdynamic` at the beginning of the library list. This property switches the assumption to `-Bstatic`. It is intended for use when linking an executable statically (e.g. with the GNU `-static` option).
This variable is used to initialize the target property [`LINK_SEARCH_START_STATIC`](../prop_tgt/link_search_start_static#prop_tgt:LINK_SEARCH_START_STATIC "LINK_SEARCH_START_STATIC") for all targets. If set, it’s value is also used by the [`try_compile()`](../command/try_compile#command:try_compile "try_compile") command.
See also [`CMAKE_LINK_SEARCH_END_STATIC`](cmake_link_search_end_static#variable:CMAKE_LINK_SEARCH_END_STATIC "CMAKE_LINK_SEARCH_END_STATIC").
cmake CMAKE_LINK_DEPENDS_NO_SHARED CMAKE\_LINK\_DEPENDS\_NO\_SHARED
================================
Whether to skip link dependencies on shared library files.
This variable initializes the [`LINK_DEPENDS_NO_SHARED`](../prop_tgt/link_depends_no_shared#prop_tgt:LINK_DEPENDS_NO_SHARED "LINK_DEPENDS_NO_SHARED") property on targets when they are created. See that target property for additional information.
cmake CMAKE_LINK_INTERFACE_LIBRARIES CMAKE\_LINK\_INTERFACE\_LIBRARIES
=================================
Default value for [`LINK_INTERFACE_LIBRARIES`](../prop_tgt/link_interface_libraries#prop_tgt:LINK_INTERFACE_LIBRARIES "LINK_INTERFACE_LIBRARIES") of targets.
This variable is used to initialize the [`LINK_INTERFACE_LIBRARIES`](../prop_tgt/link_interface_libraries#prop_tgt:LINK_INTERFACE_LIBRARIES "LINK_INTERFACE_LIBRARIES") property on all the targets. See that target property for additional information.
cmake CMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT CMAKE\_ECLIPSE\_GENERATE\_SOURCE\_PROJECT
=========================================
This cache variable is used by the Eclipse project generator. See [`cmake-generators(7)`](../manual/cmake-generators.7#manual:cmake-generators(7) "cmake-generators(7)").
If this variable is set to TRUE, the Eclipse project generator will generate an Eclipse project in [`CMAKE_SOURCE_DIR`](cmake_source_dir#variable:CMAKE_SOURCE_DIR "CMAKE_SOURCE_DIR") . This project can then be used in Eclipse e.g. for the version control functionality. [`CMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT`](#variable:CMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT "CMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT") defaults to FALSE; so nothing is written into the source directory.
cmake PROJECT_DESCRIPTION PROJECT\_DESCRIPTION
====================
Short project description given to the project command.
This is the description given to the most recent [`project()`](../command/project#command:project "project") command.
cmake CTEST_COVERAGE_COMMAND CTEST\_COVERAGE\_COMMAND
========================
Specify the CTest `CoverageCommand` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
Cobertura
---------
Using [Cobertura](http://cobertura.github.io/cobertura/) as the coverage generation within your multi-module Java project can generate a series of XML files.
The Cobertura Coverage parser expects to read the coverage data from a single XML file which contains the coverage data for all modules. Cobertura has a program with the ability to merge given `cobertura.ser` files and then another program to generate a combined XML file from the previous merged file. For command line testing, this can be done by hand prior to CTest looking for the coverage files. For script builds, set the `CTEST_COVERAGE_COMMAND` variable to point to a file which will perform these same steps, such as a `.sh` or `.bat` file.
```
set(CTEST_COVERAGE_COMMAND .../run-coverage-and-consolidate.sh)
```
where the `run-coverage-and-consolidate.sh` script is perhaps created by the [`configure_file()`](../command/configure_file#command:configure_file "configure_file") command and might contain the following code:
```
#!/usr/bin/env bash
CoberturaFiles="$(find "/path/to/source" -name "cobertura.ser")"
SourceDirs="$(find "/path/to/source" -name "java" -type d)"
cobertura-merge --datafile coberturamerge.ser $CoberturaFiles
cobertura-report --datafile coberturamerge.ser --destination . \
--format xml $SourceDirs
```
The script uses `find` to capture the paths to all of the `cobertura.ser` files found below the project’s source directory. It keeps the list of files and supplies it as an argument to the `cobertura-merge` program. The `--datafile` argument signifies where the result of the merge will be kept.
The combined `coberturamerge.ser` file is then used to generate the XML report using the `cobertura-report` program. The call to the cobertura-report program requires some named arguments.
`--datafila` path to the merged `.ser` file
`--destination` path to put the output files(s)
`--format` file format to write output in: xml or html The rest of the supplied arguments consist of the full paths to the `/src/main/java` directories of each module within the source tree. These directories are needed and should not be forgotten.
cmake CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY CPACK\_COMPONENT\_INCLUDE\_TOPLEVEL\_DIRECTORY
==============================================
Boolean toggle to include/exclude top level directory (component case).
Similar usage as [`CPACK_INCLUDE_TOPLEVEL_DIRECTORY`](cpack_include_toplevel_directory#variable:CPACK_INCLUDE_TOPLEVEL_DIRECTORY "CPACK_INCLUDE_TOPLEVEL_DIRECTORY") but for the component case. See [`CPACK_INCLUDE_TOPLEVEL_DIRECTORY`](cpack_include_toplevel_directory#variable:CPACK_INCLUDE_TOPLEVEL_DIRECTORY "CPACK_INCLUDE_TOPLEVEL_DIRECTORY") documentation for the detail.
cmake CMAKE_ANDROID_ANT_ADDITIONAL_OPTIONS CMAKE\_ANDROID\_ANT\_ADDITIONAL\_OPTIONS
========================================
Default value for the [`ANDROID_ANT_ADDITIONAL_OPTIONS`](../prop_tgt/android_ant_additional_options#prop_tgt:ANDROID_ANT_ADDITIONAL_OPTIONS "ANDROID_ANT_ADDITIONAL_OPTIONS") target property. See that target property for additional information.
cmake PROJECT_VERSION_PATCH PROJECT\_VERSION\_PATCH
=======================
Third version number component of the [`PROJECT_VERSION`](project_version#variable:PROJECT_VERSION "PROJECT_VERSION") variable as set by the [`project()`](../command/project#command:project "project") command.
cmake CMAKE_OBJECT_PATH_MAX CMAKE\_OBJECT\_PATH\_MAX
========================
Maximum object file full-path length allowed by native build tools.
CMake computes for every source file an object file name that is unique to the source file and deterministic with respect to the full path to the source file. This allows multiple source files in a target to share the same name if they lie in different directories without rebuilding when one is added or removed. However, it can produce long full paths in a few cases, so CMake shortens the path using a hashing scheme when the full path to an object file exceeds a limit. CMake has a built-in limit for each platform that is sufficient for common tools, but some native tools may have a lower limit. This variable may be set to specify the limit explicitly. The value must be an integer no less than 128.
cmake XCODE XCODE
=====
`True` when using [`Xcode`](https://cmake.org/cmake/help/v3.9/generator/Xcode.html#generator:Xcode "Xcode") generator.
cmake CMAKE_MODULE_LINKER_FLAGS CMAKE\_MODULE\_LINKER\_FLAGS
============================
Linker flags to be used to create modules.
These flags will be used by the linker when creating a module.
cmake CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD CMAKE\_VS\_INCLUDE\_INSTALL\_TO\_DEFAULT\_BUILD
===============================================
Include `INSTALL` target to default build.
In Visual Studio solution, by default the `INSTALL` target will not be part of the default build. Setting this variable will enable the `INSTALL` target to be part of the default build.
cmake CMAKE_COLOR_MAKEFILE CMAKE\_COLOR\_MAKEFILE
======================
Enables color output when using the [Makefile Generators](../manual/cmake-generators.7#makefile-generators).
When enabled, the generated Makefiles will produce colored output. Default is `ON`.
cmake CMAKE_SHARED_LINKER_FLAGS_<CONFIG> CMAKE\_SHARED\_LINKER\_FLAGS\_<CONFIG>
======================================
Flags to be used when linking a shared library.
Same as `CMAKE_C_FLAGS_*` but used by the linker when creating shared libraries.
cmake CMAKE_TRY_COMPILE_TARGET_TYPE CMAKE\_TRY\_COMPILE\_TARGET\_TYPE
=================================
Type of target generated for [`try_compile()`](../command/try_compile#command:try_compile "try_compile") calls using the source file signature. Valid values are:
`EXECUTABLE` Use [`add_executable()`](../command/add_executable#command:add_executable "add_executable") to name the source file in the generated project. This is the default if no value is given.
`STATIC_LIBRARY` Use [`add_library()`](../command/add_library#command:add_library "add_library") with the `STATIC` option to name the source file in the generated project. This avoids running the linker and is intended for use with cross-compiling toolchains that cannot link without custom flags or linker scripts.
cmake CMAKE_EXE_LINKER_FLAGS CMAKE\_EXE\_LINKER\_FLAGS
=========================
Linker flags to be used to create executables.
These flags will be used by the linker when creating an executable.
cmake CMAKE_LINK_LIBRARY_FILE_FLAG CMAKE\_LINK\_LIBRARY\_FILE\_FLAG
================================
Flag to be used to link a library specified by a path to its file.
The flag will be used before a library file path is given to the linker. This is needed only on very few platforms.
cmake CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES CMAKE\_EXTRA\_SHARED\_LIBRARY\_SUFFIXES
=======================================
Additional suffixes for shared libraries.
Extensions for shared libraries other than that specified by [`CMAKE_SHARED_LIBRARY_SUFFIX`](cmake_shared_library_suffix#variable:CMAKE_SHARED_LIBRARY_SUFFIX "CMAKE_SHARED_LIBRARY_SUFFIX"), if any. CMake uses this to recognize external shared library files during analysis of libraries linked by a target.
cmake CTEST_BUILD_NAME CTEST\_BUILD\_NAME
==================
Specify the CTest `BuildName` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_CROSSCOMPILING CMAKE\_CROSSCOMPILING
=====================
Is CMake currently cross compiling.
This variable will be set to true by CMake if CMake is cross compiling. Specifically if the build platform is different from the target platform.
cmake CMAKE_MACOSX_BUNDLE CMAKE\_MACOSX\_BUNDLE
=====================
Default value for [`MACOSX_BUNDLE`](../prop_tgt/macosx_bundle#prop_tgt:MACOSX_BUNDLE "MACOSX_BUNDLE") of targets.
This variable is used to initialize the [`MACOSX_BUNDLE`](../prop_tgt/macosx_bundle#prop_tgt:MACOSX_BUNDLE "MACOSX_BUNDLE") property on all the targets. See that target property for additional information.
| programming_docs |
cmake CTEST_P4_COMMAND CTEST\_P4\_COMMAND
==================
Specify the CTest `P4Command` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CTEST_CUSTOM_POST_TEST CTEST\_CUSTOM\_POST\_TEST
=========================
A list of commands to run at the end of the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CMAKE_ECLIPSE_MAKE_ARGUMENTS CMAKE\_ECLIPSE\_MAKE\_ARGUMENTS
===============================
This cache variable is used by the Eclipse project generator. See [`cmake-generators(7)`](../manual/cmake-generators.7#manual:cmake-generators(7) "cmake-generators(7)").
This variable holds arguments which are used when Eclipse invokes the make tool. By default it is initialized to hold flags to enable parallel builds (using -j typically).
cmake EXECUTABLE_OUTPUT_PATH EXECUTABLE\_OUTPUT\_PATH
========================
Old executable location variable.
The target property [`RUNTIME_OUTPUT_DIRECTORY`](../prop_tgt/runtime_output_directory#prop_tgt:RUNTIME_OUTPUT_DIRECTORY "RUNTIME_OUTPUT_DIRECTORY") supercedes this variable for a target if it is set. Executable targets are otherwise placed in this directory.
cmake CMAKE_EXE_LINKER_FLAGS_INIT CMAKE\_EXE\_LINKER\_FLAGS\_INIT
===============================
Value used to initialize the [`CMAKE_EXE_LINKER_FLAGS`](cmake_exe_linker_flags#variable:CMAKE_EXE_LINKER_FLAGS "CMAKE_EXE_LINKER_FLAGS") cache entry the first time a build tree is configured. This variable is meant to be set by a [`toolchain file`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE"). CMake may prepend or append content to the value based on the environment and target platform.
See also the configuration-specific variable [`CMAKE_EXE_LINKER_FLAGS_<CONFIG>_INIT`](# "CMAKE_EXE_LINKER_FLAGS_<CONFIG>_INIT").
cmake CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD CMAKE\_VS\_INCLUDE\_PACKAGE\_TO\_DEFAULT\_BUILD
===============================================
Include `PACKAGE` target to default build.
In Visual Studio solution, by default the `PACKAGE` target will not be part of the default build. Setting this variable will enable the `PACKAGE` target to be part of the default build.
cmake CMAKE_STATIC_LIBRARY_SUFFIX CMAKE\_STATIC\_LIBRARY\_SUFFIX
==============================
The suffix for static libraries that you link to.
The suffix to use for the end of a static library filename, `.lib` on Windows.
`CMAKE_STATIC_LIBRARY_SUFFIX_<LANG>` overrides this for language `<LANG>`.
cmake CMAKE_LINK_WHAT_YOU_USE CMAKE\_LINK\_WHAT\_YOU\_USE
===========================
Default value for [`LINK_WHAT_YOU_USE`](../prop_tgt/link_what_you_use#prop_tgt:LINK_WHAT_YOU_USE "LINK_WHAT_YOU_USE") target property. This variable is used to initialize the property on each target as it is created.
cmake CMAKE_SKIP_INSTALL_ALL_DEPENDENCY CMAKE\_SKIP\_INSTALL\_ALL\_DEPENDENCY
=====================================
Don’t make the `install` target depend on the `all` target.
By default, the `install` target depends on the `all` target. This has the effect, that when `make install` is invoked or `INSTALL` is built, first the `all` target is built, then the installation starts. If [`CMAKE_SKIP_INSTALL_ALL_DEPENDENCY`](#variable:CMAKE_SKIP_INSTALL_ALL_DEPENDENCY "CMAKE_SKIP_INSTALL_ALL_DEPENDENCY") is set to `TRUE`, this dependency is not created, so the installation process will start immediately, independent from whether the project has been completely built or not.
cmake CMAKE_<LANG>_COMPILER_ABI CMAKE\_<LANG>\_COMPILER\_ABI
============================
An internal variable subject to change.
This is used in determining the compiler ABI and is subject to change.
cmake CMAKE_AUTORCC CMAKE\_AUTORCC
==============
Whether to handle `rcc` automatically for Qt targets.
This variable is used to initialize the [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC") property on all the targets. See that target property for additional information.
cmake CMAKE_C_COMPILE_FEATURES CMAKE\_C\_COMPILE\_FEATURES
===========================
List of features known to the C compiler
These features are known to be available for use with the C compiler. This list is a subset of the features listed in the [`CMAKE_C_KNOWN_FEATURES`](../prop_gbl/cmake_c_known_features#prop_gbl:CMAKE_C_KNOWN_FEATURES "CMAKE_C_KNOWN_FEATURES") global property.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
cmake CMAKE_SYSTEM_LIBRARY_PATH CMAKE\_SYSTEM\_LIBRARY\_PATH
============================
[;-list](../manual/cmake-language.7#cmake-language-lists) of directories specifying a search path for the [`find_library()`](../command/find_library#command:find_library "find_library") command. By default this contains the standard directories for the current system. It is *not* intended to be modified by the project; use [`CMAKE_LIBRARY_PATH`](cmake_library_path#variable:CMAKE_LIBRARY_PATH "CMAKE_LIBRARY_PATH") for this. See also [`CMAKE_SYSTEM_PREFIX_PATH`](cmake_system_prefix_path#variable:CMAKE_SYSTEM_PREFIX_PATH "CMAKE_SYSTEM_PREFIX_PATH").
cmake CMAKE_MACOSX_RPATH CMAKE\_MACOSX\_RPATH
====================
Whether to use rpaths on OS X and iOS.
This variable is used to initialize the [`MACOSX_RPATH`](../prop_tgt/macosx_rpath#prop_tgt:MACOSX_RPATH "MACOSX_RPATH") property on all targets.
cmake CMAKE_SOURCE_DIR CMAKE\_SOURCE\_DIR
==================
The path to the top level of the source tree.
This is the full path to the top level of the current CMake source tree. For an in-source build, this would be the same as [`CMAKE_BINARY_DIR`](cmake_binary_dir#variable:CMAKE_BINARY_DIR "CMAKE_BINARY_DIR").
When run in -P script mode, CMake sets the variables [`CMAKE_BINARY_DIR`](cmake_binary_dir#variable:CMAKE_BINARY_DIR "CMAKE_BINARY_DIR"), [`CMAKE_SOURCE_DIR`](#variable:CMAKE_SOURCE_DIR "CMAKE_SOURCE_DIR"), [`CMAKE_CURRENT_BINARY_DIR`](cmake_current_binary_dir#variable:CMAKE_CURRENT_BINARY_DIR "CMAKE_CURRENT_BINARY_DIR") and [`CMAKE_CURRENT_SOURCE_DIR`](cmake_current_source_dir#variable:CMAKE_CURRENT_SOURCE_DIR "CMAKE_CURRENT_SOURCE_DIR") to the current working directory.
cmake CMAKE_SYSTEM_IGNORE_PATH CMAKE\_SYSTEM\_IGNORE\_PATH
===========================
[;-list](../manual/cmake-language.7#cmake-language-lists) of directories to be *ignored* by the [`find_program()`](../command/find_program#command:find_program "find_program"), [`find_library()`](../command/find_library#command:find_library "find_library"), [`find_file()`](../command/find_file#command:find_file "find_file"), and [`find_path()`](../command/find_path#command:find_path "find_path") commands. This is useful in cross-compiling environments where some system directories contain incompatible but possibly linkable libraries. For example, on cross-compiled cluster environments, this allows a user to ignore directories containing libraries meant for the front-end machine.
By default this contains a list of directories containing incompatible binaries for the host system. See the [`CMAKE_IGNORE_PATH`](cmake_ignore_path#variable:CMAKE_IGNORE_PATH "CMAKE_IGNORE_PATH") variable that is intended to be set by the project.
See also the [`CMAKE_SYSTEM_PREFIX_PATH`](cmake_system_prefix_path#variable:CMAKE_SYSTEM_PREFIX_PATH "CMAKE_SYSTEM_PREFIX_PATH"), [`CMAKE_SYSTEM_LIBRARY_PATH`](cmake_system_library_path#variable:CMAKE_SYSTEM_LIBRARY_PATH "CMAKE_SYSTEM_LIBRARY_PATH"), [`CMAKE_SYSTEM_INCLUDE_PATH`](cmake_system_include_path#variable:CMAKE_SYSTEM_INCLUDE_PATH "CMAKE_SYSTEM_INCLUDE_PATH"), and [`CMAKE_SYSTEM_PROGRAM_PATH`](cmake_system_program_path#variable:CMAKE_SYSTEM_PROGRAM_PATH "CMAKE_SYSTEM_PROGRAM_PATH") variables.
cmake CTEST_CUSTOM_ERROR_PRE_CONTEXT CTEST\_CUSTOM\_ERROR\_PRE\_CONTEXT
==================================
The number of lines to include as context which precede an error message by the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command. The default is 10.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CMAKE_VS_INTEL_Fortran_PROJECT_VERSION CMAKE\_VS\_INTEL\_Fortran\_PROJECT\_VERSION
===========================================
When generating for [`Visual Studio 8 2005`](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%208%202005.html#generator:Visual%20Studio%208%202005 "Visual Studio 8 2005") or greater with the Intel Fortran plugin installed, this specifies the `.vfproj` project file format version. This is intended for internal use by CMake and should not be used by project code.
cmake CMAKE_FIND_PACKAGE_NAME CMAKE\_FIND\_PACKAGE\_NAME
==========================
Defined by the [`find_package()`](../command/find_package#command:find_package "find_package") command while loading a find module to record the caller-specified package name. See command documentation for details.
cmake CMAKE_ANDROID_ARM_MODE CMAKE\_ANDROID\_ARM\_MODE
=========================
When [Cross Compiling for Android](../manual/cmake-toolchains.7#cross-compiling-for-android) and [`CMAKE_ANDROID_ARCH_ABI`](cmake_android_arch_abi#variable:CMAKE_ANDROID_ARCH_ABI "CMAKE_ANDROID_ARCH_ABI") is set to one of the `armeabi` architectures, set `CMAKE_ANDROID_ARM_MODE` to `ON` to target 32-bit ARM processors (`-marm`). Otherwise, the default is to target the 16-bit Thumb processors (`-mthumb`).
cmake CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE CMAKE\_INCLUDE\_CURRENT\_DIR\_IN\_INTERFACE
===========================================
Automatically add the current source- and build directories to the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") target property.
If this variable is enabled, CMake automatically adds for each shared library target, static library target, module target and executable target, [`CMAKE_CURRENT_SOURCE_DIR`](cmake_current_source_dir#variable:CMAKE_CURRENT_SOURCE_DIR "CMAKE_CURRENT_SOURCE_DIR") and [`CMAKE_CURRENT_BINARY_DIR`](cmake_current_binary_dir#variable:CMAKE_CURRENT_BINARY_DIR "CMAKE_CURRENT_BINARY_DIR") to the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") target property. By default `CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE` is `OFF`.
cmake CMAKE_BACKWARDS_COMPATIBILITY CMAKE\_BACKWARDS\_COMPATIBILITY
===============================
Deprecated. See CMake Policy [`CMP0001`](../policy/cmp0001#policy:CMP0001 "CMP0001") documentation.
cmake CTEST_UPDATE_COMMAND CTEST\_UPDATE\_COMMAND
======================
Specify the CTest `UpdateCommand` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_INCLUDE_PATH CMAKE\_INCLUDE\_PATH
====================
[;-list](../manual/cmake-language.7#cmake-language-lists) of directories specifying a search path for the [`find_file()`](../command/find_file#command:find_file "find_file") and [`find_path()`](../command/find_path#command:find_path "find_path") commands. By default it is empty, it is intended to be set by the project. See also [`CMAKE_SYSTEM_INCLUDE_PATH`](cmake_system_include_path#variable:CMAKE_SYSTEM_INCLUDE_PATH "CMAKE_SYSTEM_INCLUDE_PATH") and [`CMAKE_PREFIX_PATH`](cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH").
cmake UNIX UNIX
====
`True` for UNIX and UNIX like operating systems.
Set to `true` when the target system is UNIX or UNIX like (i.e. [`APPLE`](apple#variable:APPLE "APPLE") and [`CYGWIN`](cygwin#variable:CYGWIN "CYGWIN")).
cmake CMAKE_SYSTEM_PREFIX_PATH CMAKE\_SYSTEM\_PREFIX\_PATH
===========================
[;-list](../manual/cmake-language.7#cmake-language-lists) of directories specifying installation *prefixes* to be searched by the [`find_package()`](../command/find_package#command:find_package "find_package"), [`find_program()`](../command/find_program#command:find_program "find_program"), [`find_library()`](../command/find_library#command:find_library "find_library"), [`find_file()`](../command/find_file#command:find_file "find_file"), and [`find_path()`](../command/find_path#command:find_path "find_path") commands. Each command will add appropriate subdirectories (like `bin`, `lib`, or `include`) as specified in its own documentation.
By default this contains the standard directories for the current system, the [`CMAKE_INSTALL_PREFIX`](cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX"), and the [`CMAKE_STAGING_PREFIX`](cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX"). It is *not* intended to be modified by the project; use [`CMAKE_PREFIX_PATH`](cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH") for this.
See also [`CMAKE_SYSTEM_INCLUDE_PATH`](cmake_system_include_path#variable:CMAKE_SYSTEM_INCLUDE_PATH "CMAKE_SYSTEM_INCLUDE_PATH"), [`CMAKE_SYSTEM_LIBRARY_PATH`](cmake_system_library_path#variable:CMAKE_SYSTEM_LIBRARY_PATH "CMAKE_SYSTEM_LIBRARY_PATH"), [`CMAKE_SYSTEM_PROGRAM_PATH`](cmake_system_program_path#variable:CMAKE_SYSTEM_PROGRAM_PATH "CMAKE_SYSTEM_PROGRAM_PATH"), and [`CMAKE_SYSTEM_IGNORE_PATH`](cmake_system_ignore_path#variable:CMAKE_SYSTEM_IGNORE_PATH "CMAKE_SYSTEM_IGNORE_PATH").
cmake CMAKE_BUILD_RPATH CMAKE\_BUILD\_RPATH
===================
A [;-list](../manual/cmake-language.7#cmake-language-lists) specifying runtime path (`RPATH`) entries to add to binaries linked in the build tree (for platforms that support it). The entries will *not* be used for binaries in the install tree. See also the [`CMAKE_INSTALL_RPATH`](cmake_install_rpath#variable:CMAKE_INSTALL_RPATH "CMAKE_INSTALL_RPATH") variable.
This is used to initialize the [`BUILD_RPATH`](../prop_tgt/build_rpath#prop_tgt:BUILD_RPATH "BUILD_RPATH") target property for all targets.
cmake CMAKE_POLICY_WARNING_CMP<NNNN> CMAKE\_POLICY\_WARNING\_CMP<NNNN>
=================================
Explicitly enable or disable the warning when CMake Policy `CMP<NNNN>` is not set. This is meaningful only for the few policies that do not warn by default:
* `CMAKE_POLICY_WARNING_CMP0025` controls the warning for policy [`CMP0025`](../policy/cmp0025#policy:CMP0025 "CMP0025").
* `CMAKE_POLICY_WARNING_CMP0047` controls the warning for policy [`CMP0047`](../policy/cmp0047#policy:CMP0047 "CMP0047").
* `CMAKE_POLICY_WARNING_CMP0056` controls the warning for policy [`CMP0056`](../policy/cmp0056#policy:CMP0056 "CMP0056").
* `CMAKE_POLICY_WARNING_CMP0060` controls the warning for policy [`CMP0060`](../policy/cmp0060#policy:CMP0060 "CMP0060").
* `CMAKE_POLICY_WARNING_CMP0065` controls the warning for policy [`CMP0065`](../policy/cmp0065#policy:CMP0065 "CMP0065").
* `CMAKE_POLICY_WARNING_CMP0066` controls the warning for policy [`CMP0066`](../policy/cmp0066#policy:CMP0066 "CMP0066").
* `CMAKE_POLICY_WARNING_CMP0067` controls the warning for policy [`CMP0067`](../policy/cmp0067#policy:CMP0067 "CMP0067").
This variable should not be set by a project in CMake code. Project developers running CMake may set this variable in their cache to enable the warning (e.g. `-DCMAKE_POLICY_WARNING_CMP<NNNN>=ON`). Alternatively, running [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") with the `--debug-output`, `--trace`, or `--trace-expand` option will also enable the warning.
cmake CMAKE_<LANG>_FLAGS CMAKE\_<LANG>\_FLAGS
====================
Flags for all build types.
`<LANG>` flags used regardless of the value of [`CMAKE_BUILD_TYPE`](cmake_build_type#variable:CMAKE_BUILD_TYPE "CMAKE_BUILD_TYPE").
cmake CMAKE_PROJECT_NAME CMAKE\_PROJECT\_NAME
====================
The name of the current project.
This specifies name of the current project from the closest inherited [`project()`](../command/project#command:project "project") command.
cmake CMAKE_DL_LIBS CMAKE\_DL\_LIBS
===============
Name of library containing `dlopen` and `dlclose`.
The name of the library that has `dlopen` and `dlclose` in it, usually `-ldl` on most UNIX machines.
cmake CMAKE_OSX_SYSROOT CMAKE\_OSX\_SYSROOT
===================
Specify the location or name of the OS X platform SDK to be used. CMake uses this value to compute the value of the `-isysroot` flag or equivalent and to help the `find_*` commands locate files in the SDK.
If not set explicitly the value is initialized by the `SDKROOT` environment variable, if set, and otherwise computed based on the [`CMAKE_OSX_DEPLOYMENT_TARGET`](cmake_osx_deployment_target#variable:CMAKE_OSX_DEPLOYMENT_TARGET "CMAKE_OSX_DEPLOYMENT_TARGET") or the host platform.
The value of this variable should be set prior to the first [`project()`](../command/project#command:project "project") or [`enable_language()`](../command/enable_language#command:enable_language "enable_language") command invocation because it may influence configuration of the toolchain and flags. It is intended to be set locally by the user creating a build tree.
This variable is ignored on platforms other than OS X.
cmake <PROJECT-NAME>_BINARY_DIR <PROJECT-NAME>\_BINARY\_DIR
===========================
Top level binary directory for the named project.
A variable is created with the name used in the [`project()`](../command/project#command:project "project") command, and is the binary directory for the project. This can be useful when [`add_subdirectory()`](../command/add_subdirectory#command:add_subdirectory "add_subdirectory") is used to connect several projects.
cmake CMAKE_VS_PLATFORM_TOOLSET_CUDA CMAKE\_VS\_PLATFORM\_TOOLSET\_CUDA
==================================
NVIDIA CUDA Toolkit version whose Visual Studio toolset to use.
The [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators) for VS 2010 and above support using a CUDA toolset provided by a CUDA Toolkit. The toolset version number may be specified by a field in [`CMAKE_GENERATOR_TOOLSET`](cmake_generator_toolset#variable:CMAKE_GENERATOR_TOOLSET "CMAKE_GENERATOR_TOOLSET") of the form `cuda=8.0`. If none is specified CMake will choose a default version. CMake provides the selected CUDA toolset version in this variable. The value may be empty if no CUDA Toolkit with Visual Studio integration is installed.
cmake CMAKE_Fortran_MODDIR_DEFAULT CMAKE\_Fortran\_MODDIR\_DEFAULT
===============================
Fortran default module output directory.
Most Fortran compilers write `.mod` files to the current working directory. For those that do not, this is set to `.` and used when the [`Fortran_MODULE_DIRECTORY`](../prop_tgt/fortran_module_directory#prop_tgt:Fortran_MODULE_DIRECTORY "Fortran_MODULE_DIRECTORY") target property is not set.
cmake CMAKE_GNUtoMS CMAKE\_GNUtoMS
==============
Convert GNU import libraries (`.dll.a`) to MS format (`.lib`).
This variable is used to initialize the [`GNUtoMS`](../prop_tgt/gnutoms#prop_tgt:GNUtoMS "GNUtoMS") property on targets when they are created. See that target property for additional information.
cmake CMAKE_EDIT_COMMAND CMAKE\_EDIT\_COMMAND
====================
Full path to [`cmake-gui(1)`](../manual/cmake-gui.1#manual:cmake-gui(1) "cmake-gui(1)") or [`ccmake(1)`](../manual/ccmake.1#manual:ccmake(1) "ccmake(1)"). Defined only for [Makefile Generators](../manual/cmake-generators.7#makefile-generators) when not using an “extra” generator for an IDE.
This is the full path to the CMake executable that can graphically edit the cache. For example, [`cmake-gui(1)`](../manual/cmake-gui.1#manual:cmake-gui(1) "cmake-gui(1)") or [`ccmake(1)`](../manual/ccmake.1#manual:ccmake(1) "ccmake(1)").
| programming_docs |
cmake CMAKE_VS_DEVENV_COMMAND CMAKE\_VS\_DEVENV\_COMMAND
==========================
The generators for [`Visual Studio 8 2005`](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%208%202005.html#generator:Visual%20Studio%208%202005 "Visual Studio 8 2005") and above set this variable to the `devenv.com` command installed with the corresponding Visual Studio version. Note that this variable may be empty on Visual Studio Express editions because they do not provide this tool.
This variable is not defined by other generators even if `devenv.com` is installed on the computer.
The [`CMAKE_VS_MSBUILD_COMMAND`](cmake_vs_msbuild_command#variable:CMAKE_VS_MSBUILD_COMMAND "CMAKE_VS_MSBUILD_COMMAND") is also provided for [`Visual Studio 10 2010`](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%2010%202010.html#generator:Visual%20Studio%2010%202010 "Visual Studio 10 2010") and above. See also the [`CMAKE_MAKE_PROGRAM`](cmake_make_program#variable:CMAKE_MAKE_PROGRAM "CMAKE_MAKE_PROGRAM") variable.
cmake CMAKE_ANDROID_PROGUARD_CONFIG_PATH CMAKE\_ANDROID\_PROGUARD\_CONFIG\_PATH
======================================
Default value for the [`ANDROID_PROGUARD_CONFIG_PATH`](../prop_tgt/android_proguard_config_path#prop_tgt:ANDROID_PROGUARD_CONFIG_PATH "ANDROID_PROGUARD_CONFIG_PATH") target property. See that target property for additional information.
cmake CMAKE_MFC_FLAG CMAKE\_MFC\_FLAG
================
Tell cmake to use MFC for an executable or dll.
This can be set in a `CMakeLists.txt` file and will enable MFC in the application. It should be set to `1` for the static MFC library, and `2` for the shared MFC library. This is used in Visual Studio project files. The CMakeSetup dialog used MFC and the `CMakeLists.txt` looks like this:
```
add_definitions(-D_AFXDLL)
set(CMAKE_MFC_FLAG 2)
add_executable(CMakeSetup WIN32 ${SRCS})
```
cmake CMAKE_<LANG>_ANDROID_TOOLCHAIN_MACHINE CMAKE\_<LANG>\_ANDROID\_TOOLCHAIN\_MACHINE
==========================================
When [Cross Compiling for Android](../manual/cmake-toolchains.7#cross-compiling-for-android) this variable contains the toolchain binutils machine name (e.g. `gcc -dumpmachine`). The binutils typically have a `<machine>-` prefix on their name.
See also [`CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX`](# "CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX") and [`CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX`](# "CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX").
cmake <PROJECT-NAME>_VERSION <PROJECT-NAME>\_VERSION
=======================
Value given to the `VERSION` option of the most recent call to the [`project()`](../command/project#command:project "project") command with project name `<PROJECT-NAME>`, if any.
See also the component-wise version variables [`<PROJECT-NAME>_VERSION_MAJOR`](# "<PROJECT-NAME>_VERSION_MAJOR"), [`<PROJECT-NAME>_VERSION_MINOR`](# "<PROJECT-NAME>_VERSION_MINOR"), [`<PROJECT-NAME>_VERSION_PATCH`](# "<PROJECT-NAME>_VERSION_PATCH"), and [`<PROJECT-NAME>_VERSION_TWEAK`](# "<PROJECT-NAME>_VERSION_TWEAK").
cmake CMAKE_ANDROID_PROGUARD CMAKE\_ANDROID\_PROGUARD
========================
Default value for the [`ANDROID_PROGUARD`](../prop_tgt/android_proguard#prop_tgt:ANDROID_PROGUARD "ANDROID_PROGUARD") target property. See that target property for additional information.
cmake CMAKE_AUTOMOC CMAKE\_AUTOMOC
==============
Whether to handle `moc` automatically for Qt targets.
This variable is used to initialize the [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") property on all the targets. See that target property for additional information.
cmake CMAKE_NO_SYSTEM_FROM_IMPORTED CMAKE\_NO\_SYSTEM\_FROM\_IMPORTED
=================================
Default value for [`NO_SYSTEM_FROM_IMPORTED`](../prop_tgt/no_system_from_imported#prop_tgt:NO_SYSTEM_FROM_IMPORTED "NO_SYSTEM_FROM_IMPORTED") of targets.
This variable is used to initialize the [`NO_SYSTEM_FROM_IMPORTED`](../prop_tgt/no_system_from_imported#prop_tgt:NO_SYSTEM_FROM_IMPORTED "NO_SYSTEM_FROM_IMPORTED") property on all the targets. See that target property for additional information.
cmake CMAKE_<LANG>_FLAGS_MINSIZEREL_INIT CMAKE\_<LANG>\_FLAGS\_MINSIZEREL\_INIT
======================================
Value used to initialize the [`CMAKE_<LANG>_FLAGS_MINSIZEREL`](# "CMAKE_<LANG>_FLAGS_MINSIZEREL") cache entry the first time a build tree is configured for language `<LANG>`. This variable is meant to be set by a [`toolchain file`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE"). CMake may prepend or append content to the value based on the environment and target platform.
See also [`CMAKE_<LANG>_FLAGS_INIT`](# "CMAKE_<LANG>_FLAGS_INIT").
cmake CMAKE_COMPILER_IS_GNUCC CMAKE\_COMPILER\_IS\_GNUCC
==========================
True if the `C` compiler is GNU. Use [`CMAKE_C_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") instead.
cmake <PROJECT-NAME>_VERSION_PATCH <PROJECT-NAME>\_VERSION\_PATCH
==============================
Third version number component of the [`<PROJECT-NAME>_VERSION`](# "<PROJECT-NAME>_VERSION") variable as set by the [`project()`](../command/project#command:project "project") command.
cmake CMAKE_<LANG>_CREATE_SHARED_MODULE CMAKE\_<LANG>\_CREATE\_SHARED\_MODULE
=====================================
Rule variable to create a shared module.
This is a rule variable that tells CMake how to create a shared library for the language `<LANG>`.
cmake CMAKE_GENERATOR CMAKE\_GENERATOR
================
The generator used to build the project. See [`cmake-generators(7)`](../manual/cmake-generators.7#manual:cmake-generators(7) "cmake-generators(7)").
The name of the generator that is being used to generate the build files. (e.g. `Unix Makefiles`, `Ninja`, etc.)
cmake WINDOWS_PHONE WINDOWS\_PHONE
==============
True when the [`CMAKE_SYSTEM_NAME`](cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME") variable is set to `WindowsPhone`.
cmake CMAKE_FIND_PACKAGE_SORT_DIRECTION CMAKE\_FIND\_PACKAGE\_SORT\_DIRECTION
=====================================
The sorting direction used by [`CMAKE_FIND_PACKAGE_SORT_ORDER`](cmake_find_package_sort_order#variable:CMAKE_FIND_PACKAGE_SORT_ORDER "CMAKE_FIND_PACKAGE_SORT_ORDER"). It can assume one of the following values:
`DEC` Default. Ordering is done in descending mode. The highest folder found will be tested first.
`ASC` Ordering is done in ascending mode. The lowest folder found will be tested first. If [`CMAKE_FIND_PACKAGE_SORT_ORDER`](cmake_find_package_sort_order#variable:CMAKE_FIND_PACKAGE_SORT_ORDER "CMAKE_FIND_PACKAGE_SORT_ORDER") is not set or is set to `NONE` this variable has no effect.
cmake CMAKE_AUTORCC_OPTIONS CMAKE\_AUTORCC\_OPTIONS
=======================
Whether to handle `rcc` automatically for Qt targets.
This variable is used to initialize the [`AUTORCC_OPTIONS`](../prop_tgt/autorcc_options#prop_tgt:AUTORCC_OPTIONS "AUTORCC_OPTIONS") property on all the targets. See that target property for additional information.
cmake CMAKE_CROSSCOMPILING_EMULATOR CMAKE\_CROSSCOMPILING\_EMULATOR
===============================
This variable is only used when [`CMAKE_CROSSCOMPILING`](cmake_crosscompiling#variable:CMAKE_CROSSCOMPILING "CMAKE_CROSSCOMPILING") is on. It should point to a command on the host system that can run executable built for the target system.
The command will be used to run [`try_run()`](../command/try_run#command:try_run "try_run") generated executables, which avoids manual population of the TryRunResults.cmake file.
It is also used as the default value for the [`CROSSCOMPILING_EMULATOR`](../prop_tgt/crosscompiling_emulator#prop_tgt:CROSSCOMPILING_EMULATOR "CROSSCOMPILING_EMULATOR") target property of executables.
cmake CMAKE_NOT_USING_CONFIG_FLAGS CMAKE\_NOT\_USING\_CONFIG\_FLAGS
================================
Skip `_BUILD_TYPE` flags if true.
This is an internal flag used by the generators in CMake to tell CMake to skip the `_BUILD_TYPE` flags.
cmake MSVC14 MSVC14
======
Discouraged. Use the [`MSVC_VERSION`](msvc_version#variable:MSVC_VERSION "MSVC_VERSION") variable instead.
`True` when using the Microsoft Visual Studio `v140` or `v141` toolset (`cl` version 19) or another compiler that simulates it.
cmake CTEST_CUSTOM_WARNING_EXCEPTION CTEST\_CUSTOM\_WARNING\_EXCEPTION
=================================
A list of regular expressions which will be used to exclude when detecting warning messages in build outputs by the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CMAKE_<LANG>_COMPILER_ID CMAKE\_<LANG>\_COMPILER\_ID
===========================
Compiler identification string.
A short string unique to the compiler vendor. Possible values include:
```
Absoft = Absoft Fortran (absoft.com)
ADSP = Analog VisualDSP++ (analog.com)
AppleClang = Apple Clang (apple.com)
ARMCC = ARM Compiler (arm.com)
Bruce = Bruce C Compiler
CCur = Concurrent Fortran (ccur.com)
Clang = LLVM Clang (clang.llvm.org)
Cray = Cray Compiler (cray.com)
Embarcadero, Borland = Embarcadero (embarcadero.com)
G95 = G95 Fortran (g95.org)
GNU = GNU Compiler Collection (gcc.gnu.org)
HP = Hewlett-Packard Compiler (hp.com)
Intel = Intel Compiler (intel.com)
MIPSpro = SGI MIPSpro (sgi.com)
MSVC = Microsoft Visual Studio (microsoft.com)
NVIDIA = NVIDIA CUDA Compiler (nvidia.com)
OpenWatcom = Open Watcom (openwatcom.org)
PGI = The Portland Group (pgroup.com)
PathScale = PathScale (pathscale.com)
SDCC = Small Device C Compiler (sdcc.sourceforge.net)
SunPro = Oracle Solaris Studio (oracle.com)
TI = Texas Instruments (ti.com)
TinyCC = Tiny C Compiler (tinycc.org)
XL, VisualAge, zOS = IBM XL (ibm.com)
```
This variable is not guaranteed to be defined for all compilers or languages.
cmake CMAKE_LINK_LIBRARY_SUFFIX CMAKE\_LINK\_LIBRARY\_SUFFIX
============================
The suffix for libraries that you link to.
The suffix to use for the end of a library filename, `.lib` on Windows.
cmake CMAKE_C_STANDARD_REQUIRED CMAKE\_C\_STANDARD\_REQUIRED
============================
Default value for [`C_STANDARD_REQUIRED`](../prop_tgt/c_standard_required#prop_tgt:C_STANDARD_REQUIRED "C_STANDARD_REQUIRED") property of targets.
This variable is used to initialize the [`C_STANDARD_REQUIRED`](../prop_tgt/c_standard_required#prop_tgt:C_STANDARD_REQUIRED "C_STANDARD_REQUIRED") property on all targets. See that target property for additional information.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
cmake CMAKE_PROJECT_DESCRIPTION CMAKE\_PROJECT\_DESCRIPTION
===========================
The description of the current project.
This specifies description of the current project from the closest inherited [`project()`](../command/project#command:project "project") command.
cmake CMAKE_LIBRARY_ARCHITECTURE_REGEX CMAKE\_LIBRARY\_ARCHITECTURE\_REGEX
===================================
Regex matching possible target architecture library directory names.
This is used to detect [`CMAKE_<LANG>_LIBRARY_ARCHITECTURE`](# "CMAKE_<LANG>_LIBRARY_ARCHITECTURE") from the implicit linker search path by matching the `<arch>` name.
cmake CMAKE_GENERATOR_TOOLSET CMAKE\_GENERATOR\_TOOLSET
=========================
Native build system toolset specification provided by user.
Some CMake generators support a toolset specification to tell the native build system how to choose a compiler. If the user specifies a toolset (e.g. via the [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") `-T` option) the value will be available in this variable.
The value of this variable should never be modified by project code. A toolchain file specified by the [`CMAKE_TOOLCHAIN_FILE`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE") variable may initialize `CMAKE_GENERATOR_TOOLSET`. Once a given build tree has been initialized with a particular value for this variable, changing the value has undefined behavior.
Toolset specification is supported only on specific generators:
* [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators) for VS 2010 and above
* The [`Xcode`](https://cmake.org/cmake/help/v3.9/generator/Xcode.html#generator:Xcode "Xcode") generator for Xcode 3.0 and above
See native build system documentation for allowed toolset names.
Visual Studio Toolset Selection
-------------------------------
The [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators) support toolset specification using one of these forms:
* `toolset`
* `toolset[,key=value]*`
* `key=value[,key=value]*`
The `toolset` specifies the toolset name. The selected toolset name is provided in the [`CMAKE_VS_PLATFORM_TOOLSET`](cmake_vs_platform_toolset#variable:CMAKE_VS_PLATFORM_TOOLSET "CMAKE_VS_PLATFORM_TOOLSET") variable.
The `key=value` pairs form a comma-separated list of options to specify generator-specific details of the toolset selection. Supported pairs are:
`cuda=<version>` Specify the CUDA toolkit version to use. Supported by VS 2010 and above with the CUDA toolkit VS integration installed. See the [`CMAKE_VS_PLATFORM_TOOLSET_CUDA`](cmake_vs_platform_toolset_cuda#variable:CMAKE_VS_PLATFORM_TOOLSET_CUDA "CMAKE_VS_PLATFORM_TOOLSET_CUDA") variable.
`host=x64` Request use of the native `x64` toolchain on `x64` hosts. Supported by VS 2013 and above. See the [`CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE`](cmake_vs_platform_toolset_host_architecture#variable:CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE "CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE") variable.
cmake CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES CMAKE\_CUDA\_TOOLKIT\_INCLUDE\_DIRECTORIES
==========================================
When the `CUDA` language has been enabled, this provides a [;-list](../manual/cmake-language.7#cmake-language-lists) of include directories provided by the CUDA Toolkit. The value may be useful for C++ source files to include CUDA headers.
cmake CMAKE_INCLUDE_DIRECTORIES_BEFORE CMAKE\_INCLUDE\_DIRECTORIES\_BEFORE
===================================
Whether to append or prepend directories by default in [`include_directories()`](../command/include_directories#command:include_directories "include_directories").
This variable affects the default behavior of the [`include_directories()`](../command/include_directories#command:include_directories "include_directories") command. Setting this variable to `ON` is equivalent to using the `BEFORE` option in all uses of that command.
cmake MSVC80 MSVC80
======
Discouraged. Use the [`MSVC_VERSION`](msvc_version#variable:MSVC_VERSION "MSVC_VERSION") variable instead.
`True` when using the Microsoft Visual Studio `v80` toolset (`cl` version 14) or another compiler that simulates it.
cmake CMAKE_ANDROID_STANDALONE_TOOLCHAIN CMAKE\_ANDROID\_STANDALONE\_TOOLCHAIN
=====================================
When [Cross Compiling for Android with a Standalone Toolchain](../manual/cmake-toolchains.7#cross-compiling-for-android-with-a-standalone-toolchain), this variable holds the absolute path to the root directory of the toolchain. The specified directory must contain a `sysroot` subdirectory.
cmake CMAKE_ANDROID_JAVA_SOURCE_DIR CMAKE\_ANDROID\_JAVA\_SOURCE\_DIR
=================================
Default value for the [`ANDROID_JAVA_SOURCE_DIR`](../prop_tgt/android_java_source_dir#prop_tgt:ANDROID_JAVA_SOURCE_DIR "ANDROID_JAVA_SOURCE_DIR") target property. See that target property for additional information.
cmake CMAKE_VS_PLATFORM_NAME CMAKE\_VS\_PLATFORM\_NAME
=========================
Visual Studio target platform name.
VS 8 and above allow project files to specify a target platform. CMake provides the name of the chosen platform in this variable. See the [`CMAKE_GENERATOR_PLATFORM`](cmake_generator_platform#variable:CMAKE_GENERATOR_PLATFORM "CMAKE_GENERATOR_PLATFORM") variable for details.
cmake CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION CMAKE\_ERROR\_ON\_ABSOLUTE\_INSTALL\_DESTINATION
================================================
Ask `cmake_install.cmake` script to error out as soon as a file with absolute `INSTALL DESTINATION` is encountered.
The fatal error is emitted before the installation of the offending file takes place. This variable is used by CMake-generated `cmake_install.cmake` scripts. If one sets this variable to `ON` while running the script, it may get fatal error messages from the script.
cmake CMAKE_VS_NsightTegra_VERSION CMAKE\_VS\_NsightTegra\_VERSION
===============================
When using a Visual Studio generator with the [`CMAKE_SYSTEM_NAME`](cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME") variable set to `Android`, this variable contains the version number of the installed NVIDIA Nsight Tegra Visual Studio Edition.
cmake CTEST_CUSTOM_ERROR_EXCEPTION CTEST\_CUSTOM\_ERROR\_EXCEPTION
===============================
A list of regular expressions which will be used to exclude when detecting error messages in build outputs by the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CMAKE_SYSTEM_APPBUNDLE_PATH CMAKE\_SYSTEM\_APPBUNDLE\_PATH
==============================
Search path for OS X application bundles used by the [`find_program()`](../command/find_program#command:find_program "find_program"), and [`find_package()`](../command/find_package#command:find_package "find_package") commands. By default it contains the standard directories for the current system. It is *not* intended to be modified by the project, use [`CMAKE_APPBUNDLE_PATH`](cmake_appbundle_path#variable:CMAKE_APPBUNDLE_PATH "CMAKE_APPBUNDLE_PATH") for this.
cmake CMAKE_EXE_LINKER_FLAGS_<CONFIG> CMAKE\_EXE\_LINKER\_FLAGS\_<CONFIG>
===================================
Flags to be used when linking an executable.
Same as `CMAKE_C_FLAGS_*` but used by the linker when creating executables.
cmake CTEST_SVN_OPTIONS CTEST\_SVN\_OPTIONS
===================
Specify the CTest `SVNOptions` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CPACK_SET_DESTDIR CPACK\_SET\_DESTDIR
===================
Boolean toggle to make CPack use `DESTDIR` mechanism when packaging.
`DESTDIR` means DESTination DIRectory. It is commonly used by makefile users in order to install software at non-default location. It is a basic relocation mechanism that should not be used on Windows (see [`CMAKE_INSTALL_PREFIX`](cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") documentation). It is usually invoked like this:
```
make DESTDIR=/home/john install
```
which will install the concerned software using the installation prefix, e.g. `/usr/local` prepended with the `DESTDIR` value which finally gives `/home/john/usr/local`. When preparing a package, CPack first installs the items to be packaged in a local (to the build tree) directory by using the same `DESTDIR` mechanism. Nevertheless, if `CPACK_SET_DESTDIR` is set then CPack will set `DESTDIR` before doing the local install. The most noticeable difference is that without `CPACK_SET_DESTDIR`, CPack uses [`CPACK_PACKAGING_INSTALL_PREFIX`](cpack_packaging_install_prefix#variable:CPACK_PACKAGING_INSTALL_PREFIX "CPACK_PACKAGING_INSTALL_PREFIX") as a prefix whereas with `CPACK_SET_DESTDIR` set, CPack will use [`CMAKE_INSTALL_PREFIX`](cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") as a prefix.
Manually setting `CPACK_SET_DESTDIR` may help (or simply be necessary) if some install rules uses absolute `DESTINATION` (see CMake [`install()`](../command/install#command:install "install") command). However, starting with CPack/CMake 2.8.3 RPM and DEB installers tries to handle `DESTDIR` automatically so that it is seldom necessary for the user to set it.
| programming_docs |
cmake CMAKE_<LANG>_FLAGS_MINSIZEREL CMAKE\_<LANG>\_FLAGS\_MINSIZEREL
================================
Flags for `MinSizeRel` build type or configuration.
`<LANG>` flags used when [`CMAKE_BUILD_TYPE`](cmake_build_type#variable:CMAKE_BUILD_TYPE "CMAKE_BUILD_TYPE") is `MinSizeRel` (short for minimum size release).
cmake CMAKE_XCODE_PLATFORM_TOOLSET CMAKE\_XCODE\_PLATFORM\_TOOLSET
===============================
Xcode compiler selection.
[`Xcode`](https://cmake.org/cmake/help/v3.9/generator/Xcode.html#generator:Xcode "Xcode") supports selection of a compiler from one of the installed toolsets. CMake provides the name of the chosen toolset in this variable, if any is explicitly selected (e.g. via the [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") `-T` option).
cmake CMAKE_EXTRA_GENERATOR CMAKE\_EXTRA\_GENERATOR
=======================
The extra generator used to build the project. See [`cmake-generators(7)`](../manual/cmake-generators.7#manual:cmake-generators(7) "cmake-generators(7)").
When using the Eclipse, CodeBlocks or KDevelop generators, CMake generates Makefiles ([`CMAKE_GENERATOR`](cmake_generator#variable:CMAKE_GENERATOR "CMAKE_GENERATOR")) and additionally project files for the respective IDE. This IDE project file generator is stored in `CMAKE_EXTRA_GENERATOR` (e.g. `Eclipse CDT4`).
cmake CTEST_DROP_SITE_CDASH CTEST\_DROP\_SITE\_CDASH
========================
Specify the CTest `IsCDash` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS CMAKE\_SUBLIME\_TEXT\_2\_ENV\_SETTINGS
======================================
This variable contains a list of env vars as a list of tokens with the syntax `var=value`.
Example:
```
set(CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS
"FOO=FOO1\;FOO2\;FOON"
"BAR=BAR1\;BAR2\;BARN"
"BAZ=BAZ1\;BAZ2\;BAZN"
"FOOBAR=FOOBAR1\;FOOBAR2\;FOOBARN"
"VALID="
)
```
In case of malformed variables CMake will fail:
```
set(CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS
"THIS_IS_NOT_VALID"
)
```
cmake CMAKE_FIND_PACKAGE_SORT_ORDER CMAKE\_FIND\_PACKAGE\_SORT\_ORDER
=================================
The default order for sorting packages found using [`find_package()`](../command/find_package#command:find_package "find_package"). It can assume one of the following values:
`NONE` Default. No attempt is done to sort packages. The first valid package found will be selected.
`NAME` Sort packages lexicographically before selecting one.
`NATURAL` Sort packages using natural order (see `strverscmp(3)` manual), i.e. such that contiguous digits are compared as whole numbers. Natural sorting can be employed to return the highest version when multiple versions of the same library are found by [`find_package()`](../command/find_package#command:find_package "find_package"). For example suppose that the following libraries have been found:
* libX-1.1.0
* libX-1.2.9
* libX-1.2.10
By setting `NATURAL` order we can select the one with the highest version number `libX-1.2.10`.
```
set(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL)
find_package(libX CONFIG)
```
The sort direction can be controlled using the [`CMAKE_FIND_PACKAGE_SORT_DIRECTION`](cmake_find_package_sort_direction#variable:CMAKE_FIND_PACKAGE_SORT_DIRECTION "CMAKE_FIND_PACKAGE_SORT_DIRECTION") variable (by default decrescent, e.g. lib-B will be tested before lib-A).
cmake CMAKE_FIND_LIBRARY_SUFFIXES CMAKE\_FIND\_LIBRARY\_SUFFIXES
==============================
Suffixes to append when looking for libraries.
This specifies what suffixes to add to library names when the [`find_library()`](../command/find_library#command:find_library "find_library") command looks for libraries. On Windows systems this is typically `.lib` and `.dll`, meaning that when trying to find the `foo` library it will look for `foo.dll` etc.
cmake CMAKE_STAGING_PREFIX CMAKE\_STAGING\_PREFIX
======================
This variable may be set to a path to install to when cross-compiling. This can be useful if the path in [`CMAKE_SYSROOT`](cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") is read-only, or otherwise should remain pristine.
The `CMAKE_STAGING_PREFIX` location is also used as a search prefix by the `find_*` commands. This can be controlled by setting the [`CMAKE_FIND_NO_INSTALL_PREFIX`](cmake_find_no_install_prefix#variable:CMAKE_FIND_NO_INSTALL_PREFIX "CMAKE_FIND_NO_INSTALL_PREFIX") variable.
If any RPATH/RUNPATH entries passed to the linker contain the `CMAKE_STAGING_PREFIX`, the matching path fragments are replaced with the [`CMAKE_INSTALL_PREFIX`](cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX").
cmake CMAKE_SHARED_MODULE_PREFIX CMAKE\_SHARED\_MODULE\_PREFIX
=============================
The prefix for loadable modules that you link to.
The prefix to use for the name of a loadable module on this platform.
`CMAKE_SHARED_MODULE_PREFIX_<LANG>` overrides this for language `<LANG>`.
cmake CMAKE_ARGV0 CMAKE\_ARGV0
============
Command line argument passed to CMake in script mode.
When run in [-P](../manual/cmake.1#cmake-options) script mode, CMake sets this variable to the first command line argument. It then also sets `CMAKE_ARGV1`, `CMAKE_ARGV2`, … and so on, up to the number of command line arguments given. See also [`CMAKE_ARGC`](cmake_argc#variable:CMAKE_ARGC "CMAKE_ARGC").
cmake CMAKE_HOME_DIRECTORY CMAKE\_HOME\_DIRECTORY
======================
Path to top of source tree.
This is the path to the top level of the source tree.
cmake CTEST_MEMORYCHECK_SUPPRESSIONS_FILE CTEST\_MEMORYCHECK\_SUPPRESSIONS\_FILE
======================================
Specify the CTest `MemoryCheckSuppressionFile` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_ANDROID_STL_TYPE CMAKE\_ANDROID\_STL\_TYPE
=========================
When [Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio Edition](../manual/cmake-toolchains.7#cross-compiling-for-android-with-nvidia-nsight-tegra-visual-studio-edition), this variable may be set to specify the default value for the [`ANDROID_STL_TYPE`](../prop_tgt/android_stl_type#prop_tgt:ANDROID_STL_TYPE "ANDROID_STL_TYPE") target property. See that target property for additional information.
When [Cross Compiling for Android with the NDK](../manual/cmake-toolchains.7#cross-compiling-for-android-with-the-ndk), this variable may be set to specify the STL variant to be used. The value may be one of:
`none` No C++ Support
`system` Minimal C++ without STL
`gabi++_static` GAbi++ Static
`gabi++_shared` GAbi++ Shared
`gnustl_static` GNU libstdc++ Static
`gnustl_shared` GNU libstdc++ Shared
`c++_static` LLVM libc++ Static
`c++_shared` LLVM libc++ Shared
`stlport_static` STLport Static
`stlport_shared` STLport Shared The default value is `gnustl_static`. Note that this default differs from the native NDK build system because CMake may be used to build projects for Android that are not natively implemented for it and use the C++ standard library.
cmake CMAKE_<LANG>_CREATE_STATIC_LIBRARY CMAKE\_<LANG>\_CREATE\_STATIC\_LIBRARY
======================================
Rule variable to create a static library.
This is a rule variable that tells CMake how to create a static library for the language `<LANG>`.
cmake CMAKE_JOB_POOL_COMPILE CMAKE\_JOB\_POOL\_COMPILE
=========================
This variable is used to initialize the [`JOB_POOL_COMPILE`](../prop_tgt/job_pool_compile#prop_tgt:JOB_POOL_COMPILE "JOB_POOL_COMPILE") property on all the targets. See [`JOB_POOL_COMPILE`](../prop_tgt/job_pool_compile#prop_tgt:JOB_POOL_COMPILE "JOB_POOL_COMPILE") for additional information.
cmake CTEST_CUSTOM_COVERAGE_EXCLUDE CTEST\_CUSTOM\_COVERAGE\_EXCLUDE
================================
A list of regular expressions which will be used to exclude files by their path from coverage output by the [`ctest_coverage()`](../command/ctest_coverage#command:ctest_coverage "ctest_coverage") command.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY CMAKE\_FIND\_PACKAGE\_NO\_PACKAGE\_REGISTRY
===========================================
Skip [User Package Registry](../manual/cmake-packages.7#user-package-registry) in [`find_package()`](../command/find_package#command:find_package "find_package") calls.
In some cases, for example to locate only system wide installations, it is not desirable to use the [User Package Registry](../manual/cmake-packages.7#user-package-registry) when searching for packages. If the [`CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY`](#variable:CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY "CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY") variable is enabled, all the [`find_package()`](../command/find_package#command:find_package "find_package") commands will skip the [User Package Registry](../manual/cmake-packages.7#user-package-registry) as if they were called with the `NO_CMAKE_PACKAGE_REGISTRY` argument.
See also [Disabling the Package Registry](../manual/cmake-packages.7#disabling-the-package-registry).
cmake CMAKE_EXPORT_NO_PACKAGE_REGISTRY CMAKE\_EXPORT\_NO\_PACKAGE\_REGISTRY
====================================
Disable the [`export(PACKAGE)`](../command/export#command:export "export") command.
In some cases, for example for packaging and for system wide installations, it is not desirable to write the user package registry. If the [`CMAKE_EXPORT_NO_PACKAGE_REGISTRY`](#variable:CMAKE_EXPORT_NO_PACKAGE_REGISTRY "CMAKE_EXPORT_NO_PACKAGE_REGISTRY") variable is enabled, the [`export(PACKAGE)`](../command/export#command:export "export") command will do nothing.
See also [Disabling the Package Registry](../manual/cmake-packages.7#disabling-the-package-registry).
cmake CMAKE_SKIP_BUILD_RPATH CMAKE\_SKIP\_BUILD\_RPATH
=========================
Do not include RPATHs in the build tree.
Normally CMake uses the build tree for the RPATH when building executables etc on systems that use RPATH. When the software is installed the executables etc are relinked by CMake to have the install RPATH. If this variable is set to true then the software is always built with no RPATH.
cmake CMAKE_<LANG>_LINK_EXECUTABLE CMAKE\_<LANG>\_LINK\_EXECUTABLE
===============================
Rule variable to link an executable.
Rule variable to link an executable for the given language.
cmake CMAKE_ANDROID_ARCH_ABI CMAKE\_ANDROID\_ARCH\_ABI
=========================
When [Cross Compiling for Android](../manual/cmake-toolchains.7#cross-compiling-for-android), this variable specifies the target architecture and ABI to be used. Valid values are:
* `arm64-v8a`
* `armeabi-v7a`
* `armeabi-v6`
* `armeabi`
* `mips`
* `mips64`
* `x86`
* `x86_64`
See also the [`CMAKE_ANDROID_ARM_MODE`](cmake_android_arm_mode#variable:CMAKE_ANDROID_ARM_MODE "CMAKE_ANDROID_ARM_MODE") and [`CMAKE_ANDROID_ARM_NEON`](cmake_android_arm_neon#variable:CMAKE_ANDROID_ARM_NEON "CMAKE_ANDROID_ARM_NEON") variables.
cmake CMAKE_<LANG>_IMPLICIT_LINK_LIBRARIES CMAKE\_<LANG>\_IMPLICIT\_LINK\_LIBRARIES
========================================
Implicit link libraries and flags detected for language `<LANG>`.
Compilers typically pass language runtime library names and other flags when they invoke a linker. These flags are implicit link options for the compiler’s language. CMake automatically detects these libraries and flags for each language and reports the results in this variable.
cmake CMAKE_<LANG>_IGNORE_EXTENSIONS CMAKE\_<LANG>\_IGNORE\_EXTENSIONS
=================================
File extensions that should be ignored by the build.
This is a list of file extensions that may be part of a project for a given language but are not compiled.
cmake CMAKE_TWEAK_VERSION CMAKE\_TWEAK\_VERSION
=====================
Defined to `0` for compatibility with code written for older CMake versions that may have defined higher values.
Note
In CMake versions 2.8.2 through 2.8.12, this variable holds the fourth version number component of the [`CMAKE_VERSION`](cmake_version#variable:CMAKE_VERSION "CMAKE_VERSION") variable.
cmake CMAKE_FIND_ROOT_PATH_MODE_LIBRARY CMAKE\_FIND\_ROOT\_PATH\_MODE\_LIBRARY
======================================
This variable controls whether the [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") and [`CMAKE_SYSROOT`](cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") are used by [`find_library()`](../command/find_library#command:find_library "find_library").
If set to `ONLY`, then only the roots in [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") will be searched. If set to `NEVER`, then the roots in [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") will be ignored and only the host system root will be used. If set to `BOTH`, then the host system paths and the paths in [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") will be searched.
cmake CTEST_DROP_SITE_USER CTEST\_DROP\_SITE\_USER
=======================
Specify the CTest `DropSiteUser` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_CL_64 CMAKE\_CL\_64
=============
Discouraged. Use [`CMAKE_SIZEOF_VOID_P`](cmake_sizeof_void_p#variable:CMAKE_SIZEOF_VOID_P "CMAKE_SIZEOF_VOID_P") instead.
Set to a true value when using a Microsoft Visual Studio `cl` compiler that *targets* a 64-bit architecture.
cmake CMAKE_MODULE_LINKER_FLAGS_<CONFIG>_INIT CMAKE\_MODULE\_LINKER\_FLAGS\_<CONFIG>\_INIT
============================================
Value used to initialize the [`CMAKE_MODULE_LINKER_FLAGS_<CONFIG>`](# "CMAKE_MODULE_LINKER_FLAGS_<CONFIG>") cache entry the first time a build tree is configured. This variable is meant to be set by a [`toolchain file`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE"). CMake may prepend or append content to the value based on the environment and target platform.
See also [`CMAKE_MODULE_LINKER_FLAGS_INIT`](cmake_module_linker_flags_init#variable:CMAKE_MODULE_LINKER_FLAGS_INIT "CMAKE_MODULE_LINKER_FLAGS_INIT").
cmake CTEST_TEST_LOAD CTEST\_TEST\_LOAD
=================
Specify the `TestLoad` setting in the [CTest Test Step](../manual/ctest.1#ctest-test-step) of a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script. This sets the default value for the `TEST_LOAD` option of the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command.
cmake CMAKE_<LANG>_FLAGS_RELWITHDEBINFO CMAKE\_<LANG>\_FLAGS\_RELWITHDEBINFO
====================================
Flags for `RelWithDebInfo` type or configuration.
`<LANG>` flags used when [`CMAKE_BUILD_TYPE`](cmake_build_type#variable:CMAKE_BUILD_TYPE "CMAKE_BUILD_TYPE") is `RelWithDebInfo` (short for Release With Debug Information).
cmake CTEST_P4_CLIENT CTEST\_P4\_CLIENT
=================
Specify the CTest `P4Client` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_BUILD_TOOL CMAKE\_BUILD\_TOOL
==================
This variable exists only for backwards compatibility. It contains the same value as [`CMAKE_MAKE_PROGRAM`](cmake_make_program#variable:CMAKE_MAKE_PROGRAM "CMAKE_MAKE_PROGRAM"). Use that variable instead.
cmake CMAKE_PATCH_VERSION CMAKE\_PATCH\_VERSION
=====================
Third version number component of the [`CMAKE_VERSION`](cmake_version#variable:CMAKE_VERSION "CMAKE_VERSION") variable.
cmake CMAKE_FIND_ROOT_PATH_MODE_PACKAGE CMAKE\_FIND\_ROOT\_PATH\_MODE\_PACKAGE
======================================
This variable controls whether the [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") and [`CMAKE_SYSROOT`](cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") are used by [`find_package()`](../command/find_package#command:find_package "find_package").
If set to `ONLY`, then only the roots in [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") will be searched. If set to `NEVER`, then the roots in [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") will be ignored and only the host system root will be used. If set to `BOTH`, then the host system paths and the paths in [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") will be searched.
cmake CMAKE_CODELITE_USE_TARGETS CMAKE\_CODELITE\_USE\_TARGETS
=============================
Change the way the CodeLite generator creates projectfiles.
If this variable evaluates to `ON` at the end of the top-level `CMakeLists.txt` file, the generator creates projectfiles based on targets rather than projects.
cmake CMAKE_ARCHIVE_OUTPUT_DIRECTORY CMAKE\_ARCHIVE\_OUTPUT\_DIRECTORY
=================================
Where to put all the [ARCHIVE](../manual/cmake-buildsystem.7#archive-output-artifacts) target files when built.
This variable is used to initialize the [`ARCHIVE_OUTPUT_DIRECTORY`](../prop_tgt/archive_output_directory#prop_tgt:ARCHIVE_OUTPUT_DIRECTORY "ARCHIVE_OUTPUT_DIRECTORY") property on all the targets. See that target property for additional information.
cmake CMAKE_DEPENDS_IN_PROJECT_ONLY CMAKE\_DEPENDS\_IN\_PROJECT\_ONLY
=================================
When set to `TRUE` in a directory, the build system produced by the [Makefile Generators](../manual/cmake-generators.7#makefile-generators) is set up to only consider dependencies on source files that appear either in the source or in the binary directories. Changes to source files outside of these directories will not cause rebuilds.
This should be used carefully in cases where some source files are picked up through external headers during the build.
cmake CMAKE_DEBUG_TARGET_PROPERTIES CMAKE\_DEBUG\_TARGET\_PROPERTIES
================================
Enables tracing output for target properties.
This variable can be populated with a list of properties to generate debug output for when evaluating target properties. Currently it can only be used when evaluating the [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES"), [`COMPILE_DEFINITIONS`](../prop_tgt/compile_definitions#prop_tgt:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS"), [`COMPILE_OPTIONS`](../prop_tgt/compile_options#prop_tgt:COMPILE_OPTIONS "COMPILE_OPTIONS"), [`AUTOUIC_OPTIONS`](../prop_tgt/autouic_options#prop_tgt:AUTOUIC_OPTIONS "AUTOUIC_OPTIONS"), [`SOURCES`](../prop_tgt/sources#prop_tgt:SOURCES "SOURCES"), [`COMPILE_FEATURES`](../prop_tgt/compile_features#prop_tgt:COMPILE_FEATURES "COMPILE_FEATURES"), [`POSITION_INDEPENDENT_CODE`](../prop_tgt/position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE") target properties and any other property listed in [`COMPATIBLE_INTERFACE_STRING`](../prop_tgt/compatible_interface_string#prop_tgt:COMPATIBLE_INTERFACE_STRING "COMPATIBLE_INTERFACE_STRING") and other `COMPATIBLE_INTERFACE_` properties. It outputs an origin for each entry in the target property. Default is unset.
cmake CMAKE_ANDROID_NDK_DEPRECATED_HEADERS CMAKE\_ANDROID\_NDK\_DEPRECATED\_HEADERS
========================================
When [Cross Compiling for Android with the NDK](../manual/cmake-toolchains.7#cross-compiling-for-android-with-the-ndk), this variable may be set to specify whether to use the deprecated per-api-level headers instead of the unified headers.
If not specified, the default will be *false* if using a NDK version that provides the unified headers and *true* otherwise.
| programming_docs |
cmake CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE CMAKE\_SUBLIME\_TEXT\_2\_EXCLUDE\_BUILD\_TREE
=============================================
If this variable evaluates to `ON` at the end of the top-level `CMakeLists.txt` file, the [`Sublime Text 2`](https://cmake.org/cmake/help/v3.9/generator/Sublime%20Text%202.html#generator:Sublime%20Text%202 "Sublime Text 2") extra generator excludes the build tree from the `.sublime-project` if it is inside the source tree.
cmake CMAKE_AUTOUIC_OPTIONS CMAKE\_AUTOUIC\_OPTIONS
=======================
Whether to handle `uic` automatically for Qt targets.
This variable is used to initialize the [`AUTOUIC_OPTIONS`](../prop_tgt/autouic_options#prop_tgt:AUTOUIC_OPTIONS "AUTOUIC_OPTIONS") property on all the targets. See that target property for additional information.
cmake CMAKE_<LANG>_COMPILE_OBJECT CMAKE\_<LANG>\_COMPILE\_OBJECT
==============================
Rule variable to compile a single object file.
This is a rule variable that tells CMake how to compile a single object file for the language `<LANG>`.
cmake CMAKE_INSTALL_PREFIX CMAKE\_INSTALL\_PREFIX
======================
Install directory used by [`install()`](../command/install#command:install "install").
If `make install` is invoked or `INSTALL` is built, this directory is prepended onto all install directories. This variable defaults to `/usr/local` on UNIX and `c:/Program Files/${PROJECT_NAME}` on Windows. See [`CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT`](cmake_install_prefix_initialized_to_default#variable:CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT "CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT") for how a project might choose its own default.
On UNIX one can use the `DESTDIR` mechanism in order to relocate the whole installation. `DESTDIR` means DESTination DIRectory. It is commonly used by makefile users in order to install software at non-default location. It is usually invoked like this:
```
make DESTDIR=/home/john install
```
which will install the concerned software using the installation prefix, e.g. `/usr/local` prepended with the `DESTDIR` value which finally gives `/home/john/usr/local`.
WARNING: `DESTDIR` may not be used on Windows because installation prefix usually contains a drive letter like in `C:/Program Files` which cannot be prepended with some other prefix.
The installation prefix is also added to [`CMAKE_SYSTEM_PREFIX_PATH`](cmake_system_prefix_path#variable:CMAKE_SYSTEM_PREFIX_PATH "CMAKE_SYSTEM_PREFIX_PATH") so that [`find_package()`](../command/find_package#command:find_package "find_package"), [`find_program()`](../command/find_program#command:find_program "find_program"), [`find_library()`](../command/find_library#command:find_library "find_library"), [`find_path()`](../command/find_path#command:find_path "find_path"), and [`find_file()`](../command/find_file#command:find_file "find_file") will search the prefix for other software.
Note
Use the [`GNUInstallDirs`](../module/gnuinstalldirs#module:GNUInstallDirs "GNUInstallDirs") module to provide GNU-style options for the layout of directories within the installation.
cmake CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY_<CONFIG> CMAKE\_COMPILE\_PDB\_OUTPUT\_DIRECTORY\_<CONFIG>
================================================
Per-configuration output directory for MS debug symbol `.pdb` files generated by the compiler while building source files.
This is a per-configuration version of [`CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY`](cmake_compile_pdb_output_directory#variable:CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY "CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY"). This variable is used to initialize the [`COMPILE_PDB_OUTPUT_DIRECTORY_<CONFIG>`](# "COMPILE_PDB_OUTPUT_DIRECTORY_<CONFIG>") property on all the targets.
cmake CMAKE_LIBRARY_PATH CMAKE\_LIBRARY\_PATH
====================
[;-list](../manual/cmake-language.7#cmake-language-lists) of directories specifying a search path for the [`find_library()`](../command/find_library#command:find_library "find_library") command. By default it is empty, it is intended to be set by the project. See also [`CMAKE_SYSTEM_LIBRARY_PATH`](cmake_system_library_path#variable:CMAKE_SYSTEM_LIBRARY_PATH "CMAKE_SYSTEM_LIBRARY_PATH") and [`CMAKE_PREFIX_PATH`](cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH").
cmake CTEST_SVN_UPDATE_OPTIONS CTEST\_SVN\_UPDATE\_OPTIONS
===========================
Specify the CTest `SVNUpdateOptions` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX CMAKE\_<LANG>\_ANDROID\_TOOLCHAIN\_SUFFIX
=========================================
When [Cross Compiling for Android](../manual/cmake-toolchains.7#cross-compiling-for-android) this variable contains the host platform suffix of the toolchain GNU compiler and its binutils.
See also [`CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX`](# "CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX") and [`CMAKE_<LANG>_ANDROID_TOOLCHAIN_MACHINE`](# "CMAKE_<LANG>_ANDROID_TOOLCHAIN_MACHINE").
cmake CMAKE_HOST_SOLARIS CMAKE\_HOST\_SOLARIS
====================
`True` for Oracle Solaris operating systems.
Set to `true` when the host system is Oracle Solaris.
cmake CTEST_DROP_SITE CTEST\_DROP\_SITE
=================
Specify the CTest `DropSite` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_NINJA_OUTPUT_PATH_PREFIX CMAKE\_NINJA\_OUTPUT\_PATH\_PREFIX
==================================
Set output files path prefix for the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator.
Every output files listed in the generated `build.ninja` will be prefixed by the contents of this variable (a trailing slash is appended if missing). This is useful when the generated ninja file is meant to be embedded as a `subninja` file into a *super* ninja project. For example, a ninja build file generated with a command like:
```
cd top-build-dir/sub &&
cmake -G Ninja -DCMAKE_NINJA_OUTPUT_PATH_PREFIX=sub/ path/to/source
```
can be embedded in `top-build-dir/build.ninja` with a directive like this:
```
subninja sub/build.ninja
```
The `auto-regeneration` rule in `top-build-dir/build.ninja` must have an order-only dependency on `sub/build.ninja`.
Note
When `CMAKE_NINJA_OUTPUT_PATH_PREFIX` is set, the project generated by CMake cannot be used as a standalone project. No default targets are specified.
cmake CMAKE_<LANG>_COMPILER_RANLIB CMAKE\_<LANG>\_COMPILER\_RANLIB
===============================
A wrapper around `ranlib` adding the appropriate `--plugin` option for the compiler.
See also [`CMAKE_RANLIB`](cmake_ranlib#variable:CMAKE_RANLIB "CMAKE_RANLIB").
cmake CMAKE_SHARED_LIBRARY_SUFFIX CMAKE\_SHARED\_LIBRARY\_SUFFIX
==============================
The suffix for shared libraries that you link to.
The suffix to use for the end of a shared library filename, `.dll` on Windows.
`CMAKE_SHARED_LIBRARY_SUFFIX_<LANG>` overrides this for language `<LANG>`.
cmake PROJECT_BINARY_DIR PROJECT\_BINARY\_DIR
====================
Full path to build directory for project.
This is the binary directory of the most recent [`project()`](../command/project#command:project "project") command.
cmake CMAKE_Fortran_MODDIR_FLAG CMAKE\_Fortran\_MODDIR\_FLAG
============================
Fortran flag for module output directory.
This stores the flag needed to pass the value of the [`Fortran_MODULE_DIRECTORY`](../prop_tgt/fortran_module_directory#prop_tgt:Fortran_MODULE_DIRECTORY "Fortran_MODULE_DIRECTORY") target property to the compiler.
cmake CMAKE_FIND_ROOT_PATH_MODE_INCLUDE CMAKE\_FIND\_ROOT\_PATH\_MODE\_INCLUDE
======================================
This variable controls whether the [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") and [`CMAKE_SYSROOT`](cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") are used by [`find_file()`](../command/find_file#command:find_file "find_file") and [`find_path()`](../command/find_path#command:find_path "find_path").
If set to `ONLY`, then only the roots in [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") will be searched. If set to `NEVER`, then the roots in [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") will be ignored and only the host system root will be used. If set to `BOTH`, then the host system paths and the paths in [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") will be searched.
cmake CMAKE_Swift_LANGUAGE_VERSION CMAKE\_Swift\_LANGUAGE\_VERSION
===============================
Set to the Swift language version number. If not set, the legacy “2.3” version is assumed.
cmake CMAKE_IGNORE_PATH CMAKE\_IGNORE\_PATH
===================
[;-list](../manual/cmake-language.7#cmake-language-lists) of directories to be *ignored* by the [`find_program()`](../command/find_program#command:find_program "find_program"), [`find_library()`](../command/find_library#command:find_library "find_library"), [`find_file()`](../command/find_file#command:find_file "find_file"), and [`find_path()`](../command/find_path#command:find_path "find_path") commands. This is useful in cross-compiling environments where some system directories contain incompatible but possibly linkable libraries. For example, on cross-compiled cluster environments, this allows a user to ignore directories containing libraries meant for the front-end machine.
By default this is empty; it is intended to be set by the project. Note that `CMAKE_IGNORE_PATH` takes a list of directory names, *not* a list of prefixes. To ignore paths under prefixes (`bin`, `include`, `lib`, etc.), specify them explicitly.
See also the [`CMAKE_PREFIX_PATH`](cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH"), [`CMAKE_LIBRARY_PATH`](cmake_library_path#variable:CMAKE_LIBRARY_PATH "CMAKE_LIBRARY_PATH"), [`CMAKE_INCLUDE_PATH`](cmake_include_path#variable:CMAKE_INCLUDE_PATH "CMAKE_INCLUDE_PATH"), and [`CMAKE_PROGRAM_PATH`](cmake_program_path#variable:CMAKE_PROGRAM_PATH "CMAKE_PROGRAM_PATH") variables.
cmake MSVC12 MSVC12
======
Discouraged. Use the [`MSVC_VERSION`](msvc_version#variable:MSVC_VERSION "MSVC_VERSION") variable instead.
`True` when using the Microsoft Visual Studio `v120` toolset (`cl` version 18) or another compiler that simulates it.
cmake CTEST_DROP_LOCATION CTEST\_DROP\_LOCATION
=====================
Specify the CTest `DropLocation` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_<LANG>_LINKER_PREFERENCE_PROPAGATES CMAKE\_<LANG>\_LINKER\_PREFERENCE\_PROPAGATES
=============================================
True if [`CMAKE_<LANG>_LINKER_PREFERENCE`](# "CMAKE_<LANG>_LINKER_PREFERENCE") propagates across targets.
This is used when CMake selects a linker language for a target. Languages compiled directly into the target are always considered. A language compiled into static libraries linked by the target is considered if this variable is true.
cmake CMAKE_EXE_LINKER_FLAGS_<CONFIG>_INIT CMAKE\_EXE\_LINKER\_FLAGS\_<CONFIG>\_INIT
=========================================
Value used to initialize the [`CMAKE_EXE_LINKER_FLAGS_<CONFIG>`](# "CMAKE_EXE_LINKER_FLAGS_<CONFIG>") cache entry the first time a build tree is configured. This variable is meant to be set by a [`toolchain file`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE"). CMake may prepend or append content to the value based on the environment and target platform.
See also [`CMAKE_EXE_LINKER_FLAGS_INIT`](cmake_exe_linker_flags_init#variable:CMAKE_EXE_LINKER_FLAGS_INIT "CMAKE_EXE_LINKER_FLAGS_INIT").
cmake CMAKE_SYSTEM_INCLUDE_PATH CMAKE\_SYSTEM\_INCLUDE\_PATH
============================
[;-list](../manual/cmake-language.7#cmake-language-lists) of directories specifying a search path for the [`find_file()`](../command/find_file#command:find_file "find_file") and [`find_path()`](../command/find_path#command:find_path "find_path") commands. By default this contains the standard directories for the current system. It is *not* intended to be modified by the project; use [`CMAKE_INCLUDE_PATH`](cmake_include_path#variable:CMAKE_INCLUDE_PATH "CMAKE_INCLUDE_PATH") for this. See also [`CMAKE_SYSTEM_PREFIX_PATH`](cmake_system_prefix_path#variable:CMAKE_SYSTEM_PREFIX_PATH "CMAKE_SYSTEM_PREFIX_PATH").
cmake CMAKE_<LANG>_VISIBILITY_PRESET CMAKE\_<LANG>\_VISIBILITY\_PRESET
=================================
Default value for the [`<LANG>_VISIBILITY_PRESET`](# "<LANG>_VISIBILITY_PRESET") target property when a target is created.
cmake CMAKE_USER_MAKE_RULES_OVERRIDE_<LANG> CMAKE\_USER\_MAKE\_RULES\_OVERRIDE\_<LANG>
==========================================
Specify a CMake file that overrides platform information for `<LANG>`.
This is a language-specific version of [`CMAKE_USER_MAKE_RULES_OVERRIDE`](cmake_user_make_rules_override#variable:CMAKE_USER_MAKE_RULES_OVERRIDE "CMAKE_USER_MAKE_RULES_OVERRIDE") loaded only when enabling language `<LANG>`.
cmake CMAKE_WIN32_EXECUTABLE CMAKE\_WIN32\_EXECUTABLE
========================
Default value for [`WIN32_EXECUTABLE`](../prop_tgt/win32_executable#prop_tgt:WIN32_EXECUTABLE "WIN32_EXECUTABLE") of targets.
This variable is used to initialize the [`WIN32_EXECUTABLE`](../prop_tgt/win32_executable#prop_tgt:WIN32_EXECUTABLE "WIN32_EXECUTABLE") property on all the targets. See that target property for additional information.
cmake CMAKE_IMPORT_LIBRARY_SUFFIX CMAKE\_IMPORT\_LIBRARY\_SUFFIX
==============================
The suffix for import libraries that you link to.
The suffix to use for the end of an import library filename if used on this platform.
`CMAKE_IMPORT_LIBRARY_SUFFIX_<LANG>` overrides this for language `<LANG>`.
cmake CTEST_MEMORYCHECK_COMMAND CTEST\_MEMORYCHECK\_COMMAND
===========================
Specify the CTest `MemoryCheckCommand` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_PREFIX_PATH CMAKE\_PREFIX\_PATH
===================
[;-list](../manual/cmake-language.7#cmake-language-lists) of directories specifying installation *prefixes* to be searched by the [`find_package()`](../command/find_package#command:find_package "find_package"), [`find_program()`](../command/find_program#command:find_program "find_program"), [`find_library()`](../command/find_library#command:find_library "find_library"), [`find_file()`](../command/find_file#command:find_file "find_file"), and [`find_path()`](../command/find_path#command:find_path "find_path") commands. Each command will add appropriate subdirectories (like `bin`, `lib`, or `include`) as specified in its own documentation.
By default this is empty. It is intended to be set by the project.
See also [`CMAKE_SYSTEM_PREFIX_PATH`](cmake_system_prefix_path#variable:CMAKE_SYSTEM_PREFIX_PATH "CMAKE_SYSTEM_PREFIX_PATH"), [`CMAKE_INCLUDE_PATH`](cmake_include_path#variable:CMAKE_INCLUDE_PATH "CMAKE_INCLUDE_PATH"), [`CMAKE_LIBRARY_PATH`](cmake_library_path#variable:CMAKE_LIBRARY_PATH "CMAKE_LIBRARY_PATH"), [`CMAKE_PROGRAM_PATH`](cmake_program_path#variable:CMAKE_PROGRAM_PATH "CMAKE_PROGRAM_PATH"), and [`CMAKE_IGNORE_PATH`](cmake_ignore_path#variable:CMAKE_IGNORE_PATH "CMAKE_IGNORE_PATH").
cmake CMAKE_FIND_APPBUNDLE CMAKE\_FIND\_APPBUNDLE
======================
This variable affects how `find_*` commands choose between OS X Application Bundles and unix-style package components.
On Darwin or systems supporting OS X Application Bundles, the `CMAKE_FIND_APPBUNDLE` variable can be set to empty or one of the following:
`FIRST` Try to find application bundles before standard programs. This is the default on Darwin.
`LAST` Try to find application bundles after standard programs.
`ONLY` Only try to find application bundles.
`NEVER` Never try to find application bundles.
cmake CMAKE_ECLIPSE_VERSION CMAKE\_ECLIPSE\_VERSION
=======================
This cache variable is used by the Eclipse project generator. See [`cmake-generators(7)`](../manual/cmake-generators.7#manual:cmake-generators(7) "cmake-generators(7)").
When using the Eclipse project generator, CMake tries to find the Eclipse executable and detect the version of it. Depending on the version it finds, some features are enabled or disabled. If CMake doesn’t find Eclipse, it assumes the oldest supported version, Eclipse Callisto (3.2).
cmake CMAKE_CFG_INTDIR CMAKE\_CFG\_INTDIR
==================
Build-time reference to per-configuration output subdirectory.
For native build systems supporting multiple configurations in the build tree (such as [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators) and [`Xcode`](https://cmake.org/cmake/help/v3.9/generator/Xcode.html#generator:Xcode "Xcode")), the value is a reference to a build-time variable specifying the name of the per-configuration output subdirectory. On [Makefile Generators](../manual/cmake-generators.7#makefile-generators) this evaluates to `.` because there is only one configuration in a build tree. Example values:
```
$(ConfigurationName) = Visual Studio 8, 9
$(Configuration) = Visual Studio 10
$(CONFIGURATION) = Xcode
. = Make-based tools
```
Since these values are evaluated by the native build system, this variable is suitable only for use in command lines that will be evaluated at build time. Example of intended usage:
```
add_executable(mytool mytool.c)
add_custom_command(
OUTPUT out.txt
COMMAND ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/mytool
${CMAKE_CURRENT_SOURCE_DIR}/in.txt out.txt
DEPENDS mytool in.txt
)
add_custom_target(drive ALL DEPENDS out.txt)
```
Note that `CMAKE_CFG_INTDIR` is no longer necessary for this purpose but has been left for compatibility with existing projects. Instead [`add_custom_command()`](../command/add_custom_command#command:add_custom_command "add_custom_command") recognizes executable target names in its `COMMAND` option, so `${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/mytool` can be replaced by just `mytool`.
This variable is read-only. Setting it is undefined behavior. In multi-configuration build systems the value of this variable is passed as the value of preprocessor symbol `CMAKE_INTDIR` to the compilation of all source files.
cmake CMAKE_SHARED_LINKER_FLAGS_INIT CMAKE\_SHARED\_LINKER\_FLAGS\_INIT
==================================
Value used to initialize the [`CMAKE_SHARED_LINKER_FLAGS`](cmake_shared_linker_flags#variable:CMAKE_SHARED_LINKER_FLAGS "CMAKE_SHARED_LINKER_FLAGS") cache entry the first time a build tree is configured. This variable is meant to be set by a [`toolchain file`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE"). CMake may prepend or append content to the value based on the environment and target platform.
See also the configuration-specific variable [`CMAKE_SHARED_LINKER_FLAGS_<CONFIG>_INIT`](# "CMAKE_SHARED_LINKER_FLAGS_<CONFIG>_INIT").
cmake MSVC90 MSVC90
======
Discouraged. Use the [`MSVC_VERSION`](msvc_version#variable:MSVC_VERSION "MSVC_VERSION") variable instead.
`True` when using the Microsoft Visual Studio `v90` toolset (`cl` version 15) or another compiler that simulates it.
cmake CMAKE_PDB_OUTPUT_DIRECTORY CMAKE\_PDB\_OUTPUT\_DIRECTORY
=============================
Output directory for MS debug symbol `.pdb` files generated by the linker for executable and shared library targets.
This variable is used to initialize the [`PDB_OUTPUT_DIRECTORY`](../prop_tgt/pdb_output_directory#prop_tgt:PDB_OUTPUT_DIRECTORY "PDB_OUTPUT_DIRECTORY") property on all the targets. See that target property for additional information.
cmake CMAKE_CXX_STANDARD CMAKE\_CXX\_STANDARD
====================
Default value for [`CXX_STANDARD`](../prop_tgt/cxx_standard#prop_tgt:CXX_STANDARD "CXX_STANDARD") property of targets.
This variable is used to initialize the [`CXX_STANDARD`](../prop_tgt/cxx_standard#prop_tgt:CXX_STANDARD "CXX_STANDARD") property on all targets. See that target property for additional information.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
| programming_docs |
cmake CMAKE_SKIP_RPATH CMAKE\_SKIP\_RPATH
==================
If true, do not add run time path information.
If this is set to `TRUE`, then the rpath information is not added to compiled executables. The default is to add rpath information if the platform supports it. This allows for easy running from the build tree. To omit RPATH in the install step, but not the build step, use [`CMAKE_SKIP_INSTALL_RPATH`](cmake_skip_install_rpath#variable:CMAKE_SKIP_INSTALL_RPATH "CMAKE_SKIP_INSTALL_RPATH") instead.
cmake CMAKE_<LANG>_GHS_KERNEL_FLAGS_DEBUG CMAKE\_<LANG>\_GHS\_KERNEL\_FLAGS\_DEBUG
========================================
GHS kernel flags for `Debug` build type or configuration.
`<LANG>` flags used when [`CMAKE_BUILD_TYPE`](cmake_build_type#variable:CMAKE_BUILD_TYPE "CMAKE_BUILD_TYPE") is `Debug`.
cmake CMAKE_SCRIPT_MODE_FILE CMAKE\_SCRIPT\_MODE\_FILE
=========================
Full path to the [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") `-P` script file currently being processed.
When run in [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") `-P` script mode, CMake sets this variable to the full path of the script file. When run to configure a `CMakeLists.txt` file, this variable is not set.
cmake CMAKE_LIBRARY_OUTPUT_DIRECTORY CMAKE\_LIBRARY\_OUTPUT\_DIRECTORY
=================================
Where to put all the [LIBRARY](../manual/cmake-buildsystem.7#library-output-artifacts) target files when built.
This variable is used to initialize the [`LIBRARY_OUTPUT_DIRECTORY`](../prop_tgt/library_output_directory#prop_tgt:LIBRARY_OUTPUT_DIRECTORY "LIBRARY_OUTPUT_DIRECTORY") property on all the targets. See that target property for additional information.
cmake CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX CMAKE\_FIND\_LIBRARY\_CUSTOM\_LIB\_SUFFIX
=========================================
Specify a `<suffix>` to tell the [`find_library()`](../command/find_library#command:find_library "find_library") command to search in a `lib<suffix>` directory before each `lib` directory that would normally be searched.
This overrides the behavior of related global properties:
* [`FIND_LIBRARY_USE_LIB32_PATHS`](../prop_gbl/find_library_use_lib32_paths#prop_gbl:FIND_LIBRARY_USE_LIB32_PATHS "FIND_LIBRARY_USE_LIB32_PATHS")
* [`FIND_LIBRARY_USE_LIB64_PATHS`](../prop_gbl/find_library_use_lib64_paths#prop_gbl:FIND_LIBRARY_USE_LIB64_PATHS "FIND_LIBRARY_USE_LIB64_PATHS")
* [`FIND_LIBRARY_USE_LIBX32_PATHS`](../prop_gbl/find_library_use_libx32_paths#prop_gbl:FIND_LIBRARY_USE_LIBX32_PATHS "FIND_LIBRARY_USE_LIBX32_PATHS")
cmake CMAKE_<LANG>_PLATFORM_ID CMAKE\_<LANG>\_PLATFORM\_ID
===========================
An internal variable subject to change.
This is used in determining the platform and is subject to change.
cmake CMAKE_SYSROOT_COMPILE CMAKE\_SYSROOT\_COMPILE
=======================
Path to pass to the compiler in the `--sysroot` flag when compiling source files. This is the same as [`CMAKE_SYSROOT`](cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") but is used only for compiling sources and not linking.
This variable may only be set in a toolchain file specified by the [`CMAKE_TOOLCHAIN_FILE`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE") variable.
cmake CTEST_BUILD_COMMAND CTEST\_BUILD\_COMMAND
=====================
Specify the CTest `MakeCommand` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_HOST_SYSTEM_PROCESSOR CMAKE\_HOST\_SYSTEM\_PROCESSOR
==============================
The name of the CPU CMake is running on.
On systems that support `uname`, this variable is set to the output of `uname -p`. On Windows it is set to the value of the environment variable `PROCESSOR_ARCHITECTURE`.
cmake CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION CMAKE\_VS\_WINDOWS\_TARGET\_PLATFORM\_VERSION
=============================================
Visual Studio Windows Target Platform Version.
When targeting Windows 10 and above Visual Studio 2015 and above support specification of a target Windows version to select a corresponding SDK. The [`CMAKE_SYSTEM_VERSION`](cmake_system_version#variable:CMAKE_SYSTEM_VERSION "CMAKE_SYSTEM_VERSION") variable may be set to specify a version. Otherwise CMake computes a default version based on the Windows SDK versions available. The chosen Windows target version number is provided in `CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION`. If no Windows 10 SDK is available this value will be empty.
One may set a `CMAKE_WINDOWS_KITS_10_DIR` *environment variable* to an absolute path to tell CMake to look for Windows 10 SDKs in a custom location. The specified directory is expected to contain `Include/10.0.*` directories.
cmake CTEST_GIT_INIT_SUBMODULES CTEST\_GIT\_INIT\_SUBMODULES
============================
Specify the CTest `GITInitSubmodules` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_ERROR_DEPRECATED CMAKE\_ERROR\_DEPRECATED
========================
Whether to issue errors for deprecated functionality.
If `TRUE`, use of deprecated functionality will issue fatal errors. If this variable is not set, CMake behaves as if it were set to `FALSE`.
cmake CMAKE_FIND_NO_INSTALL_PREFIX CMAKE\_FIND\_NO\_INSTALL\_PREFIX
================================
Ignore the [`CMAKE_INSTALL_PREFIX`](cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") when searching for assets.
CMake adds the [`CMAKE_INSTALL_PREFIX`](cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") and the [`CMAKE_STAGING_PREFIX`](cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX") variable to the [`CMAKE_SYSTEM_PREFIX_PATH`](cmake_system_prefix_path#variable:CMAKE_SYSTEM_PREFIX_PATH "CMAKE_SYSTEM_PREFIX_PATH") by default. This variable may be set on the command line to control that behavior.
Set `CMAKE_FIND_NO_INSTALL_PREFIX` to `TRUE` to tell [`find_package()`](../command/find_package#command:find_package "find_package") not to search in the [`CMAKE_INSTALL_PREFIX`](cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") or [`CMAKE_STAGING_PREFIX`](cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX") by default. Note that the prefix may still be searched for other reasons, such as being the same prefix as the CMake installation, or for being a built-in system prefix.
cmake CMAKE_MINOR_VERSION CMAKE\_MINOR\_VERSION
=====================
Second version number component of the [`CMAKE_VERSION`](cmake_version#variable:CMAKE_VERSION "CMAKE_VERSION") variable.
cmake CMAKE_SYSROOT CMAKE\_SYSROOT
==============
Path to pass to the compiler in the `--sysroot` flag.
The `CMAKE_SYSROOT` content is passed to the compiler in the `--sysroot` flag, if supported. The path is also stripped from the RPATH/RUNPATH if necessary on installation. The `CMAKE_SYSROOT` is also used to prefix paths searched by the `find_*` commands.
This variable may only be set in a toolchain file specified by the [`CMAKE_TOOLCHAIN_FILE`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE") variable.
See also the [`CMAKE_SYSROOT_COMPILE`](cmake_sysroot_compile#variable:CMAKE_SYSROOT_COMPILE "CMAKE_SYSROOT_COMPILE") and [`CMAKE_SYSROOT_LINK`](cmake_sysroot_link#variable:CMAKE_SYSROOT_LINK "CMAKE_SYSROOT_LINK") variables.
cmake CMAKE_ECLIPSE_GENERATE_LINKED_RESOURCES CMAKE\_ECLIPSE\_GENERATE\_LINKED\_RESOURCES
===========================================
This cache variable is used by the Eclipse project generator. See [`cmake-generators(7)`](../manual/cmake-generators.7#manual:cmake-generators(7) "cmake-generators(7)").
The Eclipse project generator generates so-called linked resources e.g. to the subproject root dirs in the source tree or to the source files of targets. This can be disabled by setting this variable to FALSE.
cmake CMAKE_CURRENT_BINARY_DIR CMAKE\_CURRENT\_BINARY\_DIR
===========================
The path to the binary directory currently being processed.
This the full path to the build directory that is currently being processed by cmake. Each directory added by [`add_subdirectory()`](../command/add_subdirectory#command:add_subdirectory "add_subdirectory") will create a binary directory in the build tree, and as it is being processed this variable will be set. For in-source builds this is the current source directory being processed.
When run in -P script mode, CMake sets the variables [`CMAKE_BINARY_DIR`](cmake_binary_dir#variable:CMAKE_BINARY_DIR "CMAKE_BINARY_DIR"), [`CMAKE_SOURCE_DIR`](cmake_source_dir#variable:CMAKE_SOURCE_DIR "CMAKE_SOURCE_DIR"), [`CMAKE_CURRENT_BINARY_DIR`](#variable:CMAKE_CURRENT_BINARY_DIR "CMAKE_CURRENT_BINARY_DIR") and [`CMAKE_CURRENT_SOURCE_DIR`](cmake_current_source_dir#variable:CMAKE_CURRENT_SOURCE_DIR "CMAKE_CURRENT_SOURCE_DIR") to the current working directory.
cmake CMAKE_NO_BUILTIN_CHRPATH CMAKE\_NO\_BUILTIN\_CHRPATH
===========================
Do not use the builtin ELF editor to fix RPATHs on installation.
When an ELF binary needs to have a different RPATH after installation than it does in the build tree, CMake uses a builtin editor to change the RPATH in the installed copy. If this variable is set to true then CMake will relink the binary before installation instead of using its builtin editor.
cmake CMAKE_MATCH_<n> CMAKE\_MATCH\_<n>
=================
Capture group `<n>` matched by the last regular expression, for groups 0 through 9. Group 0 is the entire match. Groups 1 through 9 are the subexpressions captured by `()` syntax.
When a regular expression match is used, CMake fills in `CMAKE_MATCH_<n>` variables with the match contents. The [`CMAKE_MATCH_COUNT`](cmake_match_count#variable:CMAKE_MATCH_COUNT "CMAKE_MATCH_COUNT") variable holds the number of match expressions when these are filled.
cmake CMAKE_<LANG>_OUTPUT_EXTENSION CMAKE\_<LANG>\_OUTPUT\_EXTENSION
================================
Extension for the output of a compile for a single file.
This is the extension for an object file for the given `<LANG>`. For example `.obj` for C on Windows.
cmake CMAKE_SYSTEM_NAME CMAKE\_SYSTEM\_NAME
===================
The name of the operating system for which CMake is to build. See the [`CMAKE_SYSTEM_VERSION`](cmake_system_version#variable:CMAKE_SYSTEM_VERSION "CMAKE_SYSTEM_VERSION") variable for the OS version.
System Name for Host Builds
---------------------------
`CMAKE_SYSTEM_NAME` is by default set to the same value as the [`CMAKE_HOST_SYSTEM_NAME`](cmake_host_system_name#variable:CMAKE_HOST_SYSTEM_NAME "CMAKE_HOST_SYSTEM_NAME") variable so that the build targets the host system.
System Name for Cross Compiling
-------------------------------
`CMAKE_SYSTEM_NAME` may be set explicitly when first configuring a new build tree in order to enable [cross compiling](../manual/cmake-toolchains.7#cross-compiling-toolchain). In this case the [`CMAKE_SYSTEM_VERSION`](cmake_system_version#variable:CMAKE_SYSTEM_VERSION "CMAKE_SYSTEM_VERSION") variable must also be set explicitly.
cmake CMAKE_TOOLCHAIN_FILE CMAKE\_TOOLCHAIN\_FILE
======================
Path to toolchain file supplied to [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)").
This variable is specified on the command line when cross-compiling with CMake. It is the path to a file which is read early in the CMake run and which specifies locations for compilers and toolchain utilities, and other target platform and compiler related information.
cmake CMAKE_STATIC_LINKER_FLAGS_<CONFIG> CMAKE\_STATIC\_LINKER\_FLAGS\_<CONFIG>
======================================
Flags to be used when linking a static library.
Same as `CMAKE_C_FLAGS_*` but used by the linker when creating static libraries.
cmake CMAKE_<LANG>_LINKER_PREFERENCE CMAKE\_<LANG>\_LINKER\_PREFERENCE
=================================
Preference value for linker language selection.
The “linker language” for executable, shared library, and module targets is the language whose compiler will invoke the linker. The [`LINKER_LANGUAGE`](../prop_tgt/linker_language#prop_tgt:LINKER_LANGUAGE "LINKER_LANGUAGE") target property sets the language explicitly. Otherwise, the linker language is that whose linker preference value is highest among languages compiled and linked into the target. See also the [`CMAKE_<LANG>_LINKER_PREFERENCE_PROPAGATES`](# "CMAKE_<LANG>_LINKER_PREFERENCE_PROPAGATES") variable.
cmake WINCE WINCE
=====
True when the [`CMAKE_SYSTEM_NAME`](cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME") variable is set to `WindowsCE`.
cmake CMAKE_<LANG>_CPPLINT CMAKE\_<LANG>\_CPPLINT
======================
Default value for [`<LANG>_CPPLINT`](# "<LANG>_CPPLINT") target property. This variable is used to initialize the property on each target as it is created. This is done only when `<LANG>` is `C` or `CXX`.
cmake CTEST_BINARY_DIRECTORY CTEST\_BINARY\_DIRECTORY
========================
Specify the CTest `BuildDirectory` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_VERSION CMAKE\_VERSION
==============
The CMake version string as three non-negative integer components separated by `.` and possibly followed by `-` and other information. The first two components represent the feature level and the third component represents either a bug-fix level or development date.
Release versions and release candidate versions of CMake use the format:
```
<major>.<minor>.<patch>[-rc<n>]
```
where the `<patch>` component is less than `20000000`. Development versions of CMake use the format:
```
<major>.<minor>.<date>[-<id>]
```
where the `<date>` component is of format `CCYYMMDD` and `<id>` may contain arbitrary text. This represents development as of a particular date following the `<major>.<minor>` feature release.
Individual component values are also available in variables:
* [`CMAKE_MAJOR_VERSION`](cmake_major_version#variable:CMAKE_MAJOR_VERSION "CMAKE_MAJOR_VERSION")
* [`CMAKE_MINOR_VERSION`](cmake_minor_version#variable:CMAKE_MINOR_VERSION "CMAKE_MINOR_VERSION")
* [`CMAKE_PATCH_VERSION`](cmake_patch_version#variable:CMAKE_PATCH_VERSION "CMAKE_PATCH_VERSION")
* [`CMAKE_TWEAK_VERSION`](cmake_tweak_version#variable:CMAKE_TWEAK_VERSION "CMAKE_TWEAK_VERSION")
Use the [`if()`](../command/if#command:if "if") command `VERSION_LESS`, `VERSION_GREATER`, `VERSION_EQUAL`, `VERSION_LESS_EQUAL`, or `VERSION_GREATER_EQUAL` operators to compare version string values against `CMAKE_VERSION` using a component-wise test. Version component values may be 10 or larger so do not attempt to compare version strings as floating-point numbers.
Note
CMake versions 2.8.2 through 2.8.12 used three components for the feature level. Release versions represented the bug-fix level in a fourth component, i.e. `<major>.<minor>.<patch>[.<tweak>][-rc<n>]`. Development versions represented the development date in the fourth component, i.e. `<major>.<minor>.<patch>.<date>[-<id>]`.
CMake versions prior to 2.8.2 used three components for the feature level and had no bug-fix component. Release versions used an even-valued second component, i.e. `<major>.<even-minor>.<patch>[-rc<n>]`. Development versions used an odd-valued second component with the development date as the third component, i.e. `<major>.<odd-minor>.<date>`.
The `CMAKE_VERSION` variable is defined by CMake 2.6.3 and higher. Earlier versions defined only the individual component variables.
cmake CMAKE_APPBUNDLE_PATH CMAKE\_APPBUNDLE\_PATH
======================
[;-list](../manual/cmake-language.7#cmake-language-lists) of directories specifying a search path for OS X application bundles used by the [`find_program()`](../command/find_program#command:find_program "find_program"), and [`find_package()`](../command/find_package#command:find_package "find_package") commands.
cmake CMAKE_VS_PLATFORM_TOOLSET CMAKE\_VS\_PLATFORM\_TOOLSET
============================
Visual Studio Platform Toolset name.
VS 10 and above use MSBuild under the hood and support multiple compiler toolchains. CMake may specify a toolset explicitly, such as `v110` for VS 11 or `Windows7.1SDK` for 64-bit support in VS 10 Express. CMake provides the name of the chosen toolset in this variable.
See the [`CMAKE_GENERATOR_TOOLSET`](cmake_generator_toolset#variable:CMAKE_GENERATOR_TOOLSET "CMAKE_GENERATOR_TOOLSET") variable for details.
cmake CMAKE_RUNTIME_OUTPUT_DIRECTORY_<CONFIG> CMAKE\_RUNTIME\_OUTPUT\_DIRECTORY\_<CONFIG>
===========================================
Where to put all the [RUNTIME](../manual/cmake-buildsystem.7#runtime-output-artifacts) target files when built for a specific configuration.
This variable is used to initialize the [`RUNTIME_OUTPUT_DIRECTORY_<CONFIG>`](# "RUNTIME_OUTPUT_DIRECTORY_<CONFIG>") property on all the targets. See that target property for additional information.
cmake CMAKE_CACHE_PATCH_VERSION CMAKE\_CACHE\_PATCH\_VERSION
============================
Patch version of CMake used to create the `CMakeCache.txt` file
This stores the patch version of CMake used to write a CMake cache file. It is only different when a different version of CMake is run on a previously created cache file.
cmake CTEST_UPDATE_OPTIONS CTEST\_UPDATE\_OPTIONS
======================
Specify the CTest `UpdateOptions` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CTEST_CUSTOM_PRE_MEMCHECK CTEST\_CUSTOM\_PRE\_MEMCHECK
============================
A list of commands to run at the start of the [`ctest_memcheck()`](../command/ctest_memcheck#command:ctest_memcheck "ctest_memcheck") command.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CTEST_MEMORYCHECK_SANITIZER_OPTIONS CTEST\_MEMORYCHECK\_SANITIZER\_OPTIONS
======================================
Specify the CTest `MemoryCheckSanitizerOptions` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake MSVC_IDE MSVC\_IDE
=========
`True` when using the Microsoft Visual C++ IDE.
Set to `true` when the target platform is the Microsoft Visual C++ IDE, as opposed to the command line compiler.
cmake CMAKE_ANDROID_NATIVE_LIB_DEPENDENCIES CMAKE\_ANDROID\_NATIVE\_LIB\_DEPENDENCIES
=========================================
Default value for the [`ANDROID_NATIVE_LIB_DEPENDENCIES`](../prop_tgt/android_native_lib_dependencies#prop_tgt:ANDROID_NATIVE_LIB_DEPENDENCIES "ANDROID_NATIVE_LIB_DEPENDENCIES") target property. See that target property for additional information.
cmake CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY CMAKE\_COMPILE\_PDB\_OUTPUT\_DIRECTORY
======================================
Output directory for MS debug symbol `.pdb` files generated by the compiler while building source files.
This variable is used to initialize the [`COMPILE_PDB_OUTPUT_DIRECTORY`](../prop_tgt/compile_pdb_output_directory#prop_tgt:COMPILE_PDB_OUTPUT_DIRECTORY "COMPILE_PDB_OUTPUT_DIRECTORY") property on all the targets.
cmake CMAKE_<LANG>_FLAGS_INIT CMAKE\_<LANG>\_FLAGS\_INIT
==========================
Value used to initialize the [`CMAKE_<LANG>_FLAGS`](# "CMAKE_<LANG>_FLAGS") cache entry the first time a build tree is configured for language `<LANG>`. This variable is meant to be set by a [`toolchain file`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE"). CMake may prepend or append content to the value based on the environment and target platform.
See also the configuration-specific variables:
* [`CMAKE_<LANG>_FLAGS_DEBUG_INIT`](# "CMAKE_<LANG>_FLAGS_DEBUG_INIT")
* [`CMAKE_<LANG>_FLAGS_RELEASE_INIT`](# "CMAKE_<LANG>_FLAGS_RELEASE_INIT")
* [`CMAKE_<LANG>_FLAGS_MINSIZEREL_INIT`](# "CMAKE_<LANG>_FLAGS_MINSIZEREL_INIT")
* [`CMAKE_<LANG>_FLAGS_RELWITHDEBINFO_INIT`](# "CMAKE_<LANG>_FLAGS_RELWITHDEBINFO_INIT")
| programming_docs |
cmake CMAKE_STATIC_LINKER_FLAGS_<CONFIG>_INIT CMAKE\_STATIC\_LINKER\_FLAGS\_<CONFIG>\_INIT
============================================
Value used to initialize the [`CMAKE_STATIC_LINKER_FLAGS_<CONFIG>`](# "CMAKE_STATIC_LINKER_FLAGS_<CONFIG>") cache entry the first time a build tree is configured. This variable is meant to be set by a [`toolchain file`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE"). CMake may prepend or append content to the value based on the environment and target platform.
See also [`CMAKE_STATIC_LINKER_FLAGS_INIT`](cmake_static_linker_flags_init#variable:CMAKE_STATIC_LINKER_FLAGS_INIT "CMAKE_STATIC_LINKER_FLAGS_INIT").
cmake CMAKE_AUTOMOC_MOC_OPTIONS CMAKE\_AUTOMOC\_MOC\_OPTIONS
============================
Additional options for `moc` when using [`CMAKE_AUTOMOC`](cmake_automoc#variable:CMAKE_AUTOMOC "CMAKE_AUTOMOC").
This variable is used to initialize the [`AUTOMOC_MOC_OPTIONS`](../prop_tgt/automoc_moc_options#prop_tgt:AUTOMOC_MOC_OPTIONS "AUTOMOC_MOC_OPTIONS") property on all the targets. See that target property for additional information.
cmake CMAKE_HOST_WIN32 CMAKE\_HOST\_WIN32
==================
`True` if the host system is running Windows, including Windows 64-bit and MSYS.
Set to `false` on Cygwin.
cmake PROJECT_VERSION_TWEAK PROJECT\_VERSION\_TWEAK
=======================
Fourth version number component of the [`PROJECT_VERSION`](project_version#variable:PROJECT_VERSION "PROJECT_VERSION") variable as set by the [`project()`](../command/project#command:project "project") command.
cmake CMAKE_AUTOMOC_RELAXED_MODE CMAKE\_AUTOMOC\_RELAXED\_MODE
=============================
Switch between strict and relaxed automoc mode.
By default, [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") behaves exactly as described in the documentation of the [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") target property. When set to `TRUE`, it accepts more input and tries to find the correct input file for `moc` even if it differs from the documented behaviour. In this mode it e.g. also checks whether a header file is intended to be processed by moc when a `"foo.moc"` file has been included.
Relaxed mode has to be enabled for KDE4 compatibility.
cmake CTEST_GIT_COMMAND CTEST\_GIT\_COMMAND
===================
Specify the CTest `GITCommand` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_Fortran_MODULE_DIRECTORY CMAKE\_Fortran\_MODULE\_DIRECTORY
=================================
Fortran module output directory.
This variable is used to initialize the [`Fortran_MODULE_DIRECTORY`](../prop_tgt/fortran_module_directory#prop_tgt:Fortran_MODULE_DIRECTORY "Fortran_MODULE_DIRECTORY") property on all the targets. See that target property for additional information.
cmake CMAKE_FIND_LIBRARY_PREFIXES CMAKE\_FIND\_LIBRARY\_PREFIXES
==============================
Prefixes to prepend when looking for libraries.
This specifies what prefixes to add to library names when the [`find_library()`](../command/find_library#command:find_library "find_library") command looks for libraries. On UNIX systems this is typically `lib`, meaning that when trying to find the `foo` library it will look for `libfoo`.
cmake MSVC70 MSVC70
======
Discouraged. Use the [`MSVC_VERSION`](msvc_version#variable:MSVC_VERSION "MSVC_VERSION") variable instead.
`True` when using Microsoft Visual C++ 7.0.
Set to `true` when the compiler is version 7.0 of Microsoft Visual C++.
cmake CMAKE_MATCH_COUNT CMAKE\_MATCH\_COUNT
===================
The number of matches with the last regular expression.
When a regular expression match is used, CMake fills in [`CMAKE_MATCH_<n>`](# "CMAKE_MATCH_<n>") variables with the match contents. The `CMAKE_MATCH_COUNT` variable holds the number of match expressions when these are filled.
cmake CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE CTEST\_CUSTOM\_MAXIMUM\_FAILED\_TEST\_OUTPUT\_SIZE
==================================================
When saving a failing test’s output, this is the maximum size, in bytes, that will be collected by the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command. Defaults to 307200 (300 KiB).
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CTEST_COVERAGE_EXTRA_FLAGS CTEST\_COVERAGE\_EXTRA\_FLAGS
=============================
Specify the CTest `CoverageExtraFlags` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_INSTALL_DEFAULT_COMPONENT_NAME CMAKE\_INSTALL\_DEFAULT\_COMPONENT\_NAME
========================================
Default component used in [`install()`](../command/install#command:install "install") commands.
If an [`install()`](../command/install#command:install "install") command is used without the `COMPONENT` argument, these files will be grouped into a default component. The name of this default install component will be taken from this variable. It defaults to `Unspecified`.
cmake CMAKE_FIND_ROOT_PATH_MODE_PROGRAM CMAKE\_FIND\_ROOT\_PATH\_MODE\_PROGRAM
======================================
This variable controls whether the [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") and [`CMAKE_SYSROOT`](cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") are used by [`find_program()`](../command/find_program#command:find_program "find_program").
If set to `ONLY`, then only the roots in [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") will be searched. If set to `NEVER`, then the roots in [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") will be ignored and only the host system root will be used. If set to `BOTH`, then the host system paths and the paths in [`CMAKE_FIND_ROOT_PATH`](cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") will be searched.
cmake CMAKE_CTEST_COMMAND CMAKE\_CTEST\_COMMAND
=====================
Full path to [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") command installed with CMake.
This is the full path to the CTest executable [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") which is useful from custom commands that want to use the [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") `-E` option for portable system commands.
cmake CMAKE_COMPILER_2005 CMAKE\_COMPILER\_2005
=====================
Using the Visual Studio 2005 compiler from Microsoft
Set to true when using the Visual Studio 2005 compiler from Microsoft.
cmake CMAKE_<LANG>_COMPILER_EXTERNAL_TOOLCHAIN CMAKE\_<LANG>\_COMPILER\_EXTERNAL\_TOOLCHAIN
============================================
The external toolchain for cross-compiling, if supported.
Some compiler toolchains do not ship their own auxiliary utilities such as archivers and linkers. The compiler driver may support a command-line argument to specify the location of such tools. `CMAKE_<LANG>_COMPILER_EXTERNAL_TOOLCHAIN` may be set to a path to a path to the external toolchain and will be passed to the compiler driver if supported.
This variable may only be set in a toolchain file specified by the [`CMAKE_TOOLCHAIN_FILE`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE") variable.
cmake CMAKE_AUTOUIC_SEARCH_PATHS CMAKE\_AUTOUIC\_SEARCH\_PATHS
=============================
Search path list used by [`CMAKE_AUTOUIC`](cmake_autouic#variable:CMAKE_AUTOUIC "CMAKE_AUTOUIC") to find included `.ui` files.
This variable is used to initialize the [`AUTOUIC_SEARCH_PATHS`](../prop_tgt/autouic_search_paths#prop_tgt:AUTOUIC_SEARCH_PATHS "AUTOUIC_SEARCH_PATHS") property on all the targets. See that target property for additional information.
By default it is empty.
cmake CMAKE_<LANG>_ARCHIVE_APPEND CMAKE\_<LANG>\_ARCHIVE\_APPEND
==============================
Rule variable to append to a static archive.
This is a rule variable that tells CMake how to append to a static archive. It is used in place of [`CMAKE_<LANG>_CREATE_STATIC_LIBRARY`](# "CMAKE_<LANG>_CREATE_STATIC_LIBRARY") on some platforms in order to support large object counts. See also [`CMAKE_<LANG>_ARCHIVE_CREATE`](# "CMAKE_<LANG>_ARCHIVE_CREATE") and [`CMAKE_<LANG>_ARCHIVE_FINISH`](# "CMAKE_<LANG>_ARCHIVE_FINISH").
cmake PROJECT_VERSION_MINOR PROJECT\_VERSION\_MINOR
=======================
Second version number component of the [`PROJECT_VERSION`](project_version#variable:PROJECT_VERSION "PROJECT_VERSION") variable as set by the [`project()`](../command/project#command:project "project") command.
cmake CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION CMAKE\_WARN\_ON\_ABSOLUTE\_INSTALL\_DESTINATION
===============================================
Ask `cmake_install.cmake` script to warn each time a file with absolute `INSTALL DESTINATION` is encountered.
This variable is used by CMake-generated `cmake_install.cmake` scripts. If one sets this variable to `ON` while running the script, it may get warning messages from the script.
cmake CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION CPACK\_WARN\_ON\_ABSOLUTE\_INSTALL\_DESTINATION
===============================================
Ask CPack to warn each time a file with absolute `INSTALL DESTINATION` is encountered.
This variable triggers the definition of [`CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION`](cmake_warn_on_absolute_install_destination#variable:CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION "CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION") when CPack runs `cmake_install.cmake` scripts.
cmake CMAKE_GENERATOR_PLATFORM CMAKE\_GENERATOR\_PLATFORM
==========================
Generator-specific target platform specification provided by user.
Some CMake generators support a target platform name to be given to the native build system to choose a compiler toolchain. If the user specifies a platform name (e.g. via the [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") `-A` option) the value will be available in this variable.
The value of this variable should never be modified by project code. A toolchain file specified by the [`CMAKE_TOOLCHAIN_FILE`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE") variable may initialize `CMAKE_GENERATOR_PLATFORM`. Once a given build tree has been initialized with a particular value for this variable, changing the value has undefined behavior.
Platform specification is supported only on specific generators:
* For [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators) with VS 2005 and above this specifies the target architecture.
See native build system documentation for allowed platform names.
Visual Studio Platform Selection
--------------------------------
On [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators) the selected platform name is provided in the [`CMAKE_VS_PLATFORM_NAME`](cmake_vs_platform_name#variable:CMAKE_VS_PLATFORM_NAME "CMAKE_VS_PLATFORM_NAME") variable.
cmake CMAKE_<LANG>_FLAGS_RELEASE_INIT CMAKE\_<LANG>\_FLAGS\_RELEASE\_INIT
===================================
Value used to initialize the [`CMAKE_<LANG>_FLAGS_RELEASE`](# "CMAKE_<LANG>_FLAGS_RELEASE") cache entry the first time a build tree is configured for language `<LANG>`. This variable is meant to be set by a [`toolchain file`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE"). CMake may prepend or append content to the value based on the environment and target platform.
See also [`CMAKE_<LANG>_FLAGS_INIT`](# "CMAKE_<LANG>_FLAGS_INIT").
cmake CMAKE_<LANG>_FLAGS_DEBUG CMAKE\_<LANG>\_FLAGS\_DEBUG
===========================
Flags for `Debug` build type or configuration.
`<LANG>` flags used when [`CMAKE_BUILD_TYPE`](cmake_build_type#variable:CMAKE_BUILD_TYPE "CMAKE_BUILD_TYPE") is `Debug`.
cmake MSVC11 MSVC11
======
Discouraged. Use the [`MSVC_VERSION`](msvc_version#variable:MSVC_VERSION "MSVC_VERSION") variable instead.
`True` when using the Microsoft Visual Studio `v110` toolset (`cl` version 17) or another compiler that simulates it.
cmake CTEST_CUSTOM_MEMCHECK_IGNORE CTEST\_CUSTOM\_MEMCHECK\_IGNORE
===============================
A list of regular expressions to use to exclude tests during the [`ctest_memcheck()`](../command/ctest_memcheck#command:ctest_memcheck "ctest_memcheck") command.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CMAKE_ANDROID_ARCH CMAKE\_ANDROID\_ARCH
====================
When [Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio Edition](../manual/cmake-toolchains.7#cross-compiling-for-android-with-nvidia-nsight-tegra-visual-studio-edition), this variable may be set to specify the default value for the [`ANDROID_ARCH`](../prop_tgt/android_arch#prop_tgt:ANDROID_ARCH "ANDROID_ARCH") target property. See that target property for additional information.
Otherwise, when [Cross Compiling for Android](../manual/cmake-toolchains.7#cross-compiling-for-android), this variable provides the name of the Android architecture corresponding to the value of the [`CMAKE_ANDROID_ARCH_ABI`](cmake_android_arch_abi#variable:CMAKE_ANDROID_ARCH_ABI "CMAKE_ANDROID_ARCH_ABI") variable. The architecture name may be one of:
* `arm`
* `arm64`
* `mips`
* `mips64`
* `x86`
* `x86_64`
cmake CMAKE_HOST_SYSTEM CMAKE\_HOST\_SYSTEM
===================
Composit Name of OS CMake is being run on.
This variable is the composite of [`CMAKE_HOST_SYSTEM_NAME`](cmake_host_system_name#variable:CMAKE_HOST_SYSTEM_NAME "CMAKE_HOST_SYSTEM_NAME") and [`CMAKE_HOST_SYSTEM_VERSION`](cmake_host_system_version#variable:CMAKE_HOST_SYSTEM_VERSION "CMAKE_HOST_SYSTEM_VERSION"), e.g. `${CMAKE_HOST_SYSTEM_NAME}-${CMAKE_HOST_SYSTEM_VERSION}`. If [`CMAKE_HOST_SYSTEM_VERSION`](cmake_host_system_version#variable:CMAKE_HOST_SYSTEM_VERSION "CMAKE_HOST_SYSTEM_VERSION") is not set, then this variable is the same as [`CMAKE_HOST_SYSTEM_NAME`](cmake_host_system_name#variable:CMAKE_HOST_SYSTEM_NAME "CMAKE_HOST_SYSTEM_NAME").
cmake CTEST_CUSTOM_TEST_IGNORE CTEST\_CUSTOM\_TEST\_IGNORE
===========================
A list of regular expressions to use to exclude tests during the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CTEST_SOURCE_DIRECTORY CTEST\_SOURCE\_DIRECTORY
========================
Specify the CTest `SourceDirectory` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_CXX_EXTENSIONS CMAKE\_CXX\_EXTENSIONS
======================
Default value for [`CXX_EXTENSIONS`](../prop_tgt/cxx_extensions#prop_tgt:CXX_EXTENSIONS "CXX_EXTENSIONS") property of targets.
This variable is used to initialize the [`CXX_EXTENSIONS`](../prop_tgt/cxx_extensions#prop_tgt:CXX_EXTENSIONS "CXX_EXTENSIONS") property on all targets. See that target property for additional information.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
cmake CMAKE_INSTALL_RPATH_USE_LINK_PATH CMAKE\_INSTALL\_RPATH\_USE\_LINK\_PATH
======================================
Add paths to linker search and installed rpath.
`CMAKE_INSTALL_RPATH_USE_LINK_PATH` is a boolean that if set to `true` will append directories in the linker search path and outside the project to the [`INSTALL_RPATH`](../prop_tgt/install_rpath#prop_tgt:INSTALL_RPATH "INSTALL_RPATH"). This is used to initialize the target property [`INSTALL_RPATH_USE_LINK_PATH`](../prop_tgt/install_rpath_use_link_path#prop_tgt:INSTALL_RPATH_USE_LINK_PATH "INSTALL_RPATH_USE_LINK_PATH") for all targets.
cmake CTEST_TRIGGER_SITE CTEST\_TRIGGER\_SITE
====================
Specify the CTest `TriggerSite` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_<LANG>_COMPILER_LAUNCHER CMAKE\_<LANG>\_COMPILER\_LAUNCHER
=================================
Default value for [`<LANG>_COMPILER_LAUNCHER`](# "<LANG>_COMPILER_LAUNCHER") target property. This variable is used to initialize the property on each target as it is created. This is done only when `<LANG>` is `C` or `CXX`.
cmake CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE CMAKE\_VS\_PLATFORM\_TOOLSET\_HOST\_ARCHITECTURE
================================================
Visual Studio preferred tool architecture.
The [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators) for VS 2013 and above support optional selection of a 64-bit toolchain on 64-bit hosts by specifying a `host=x64` value in the [`CMAKE_GENERATOR_TOOLSET`](cmake_generator_toolset#variable:CMAKE_GENERATOR_TOOLSET "CMAKE_GENERATOR_TOOLSET") option. CMake provides the selected toolchain architecture preference in this variable (either `x64` or empty).
cmake XCODE_VERSION XCODE\_VERSION
==============
Version of Xcode ([`Xcode`](https://cmake.org/cmake/help/v3.9/generator/Xcode.html#generator:Xcode "Xcode") generator only).
Under the Xcode generator, this is the version of Xcode as specified in `Xcode.app/Contents/version.plist` (such as `3.1.2`).
cmake CPACK_ABSOLUTE_DESTINATION_FILES CPACK\_ABSOLUTE\_DESTINATION\_FILES
===================================
List of files which have been installed using an `ABSOLUTE DESTINATION` path.
This variable is a Read-Only variable which is set internally by CPack during installation and before packaging using [`CMAKE_ABSOLUTE_DESTINATION_FILES`](cmake_absolute_destination_files#variable:CMAKE_ABSOLUTE_DESTINATION_FILES "CMAKE_ABSOLUTE_DESTINATION_FILES") defined in `cmake_install.cmake` scripts. The value can be used within CPack project configuration file and/or `CPack<GEN>.cmake` file of `<GEN>` generator.
cmake CMAKE_SHARED_LIBRARY_PREFIX CMAKE\_SHARED\_LIBRARY\_PREFIX
==============================
The prefix for shared libraries that you link to.
The prefix to use for the name of a shared library, `lib` on UNIX.
`CMAKE_SHARED_LIBRARY_PREFIX_<LANG>` overrides this for language `<LANG>`.
cmake CMAKE_USE_RELATIVE_PATHS CMAKE\_USE\_RELATIVE\_PATHS
===========================
This variable has no effect. The partially implemented effect it had in previous releases was removed in CMake 3.4.
cmake CMAKE_BINARY_DIR CMAKE\_BINARY\_DIR
==================
The path to the top level of the build tree.
This is the full path to the top level of the current CMake build tree. For an in-source build, this would be the same as [`CMAKE_SOURCE_DIR`](cmake_source_dir#variable:CMAKE_SOURCE_DIR "CMAKE_SOURCE_DIR").
When run in -P script mode, CMake sets the variables [`CMAKE_BINARY_DIR`](#variable:CMAKE_BINARY_DIR "CMAKE_BINARY_DIR"), [`CMAKE_SOURCE_DIR`](cmake_source_dir#variable:CMAKE_SOURCE_DIR "CMAKE_SOURCE_DIR"), [`CMAKE_CURRENT_BINARY_DIR`](cmake_current_binary_dir#variable:CMAKE_CURRENT_BINARY_DIR "CMAKE_CURRENT_BINARY_DIR") and [`CMAKE_CURRENT_SOURCE_DIR`](cmake_current_source_dir#variable:CMAKE_CURRENT_SOURCE_DIR "CMAKE_CURRENT_SOURCE_DIR") to the current working directory.
cmake CMAKE_PARENT_LIST_FILE CMAKE\_PARENT\_LIST\_FILE
=========================
Full path to the CMake file that included the current one.
While processing a CMake file loaded by [`include()`](../command/include#command:include "include") or [`find_package()`](../command/find_package#command:find_package "find_package") this variable contains the full path to the file including it. The top of the include stack is always the `CMakeLists.txt` for the current directory. See also [`CMAKE_CURRENT_LIST_FILE`](cmake_current_list_file#variable:CMAKE_CURRENT_LIST_FILE "CMAKE_CURRENT_LIST_FILE").
| programming_docs |
cmake CMAKE_ANDROID_API_MIN CMAKE\_ANDROID\_API\_MIN
========================
Default value for the [`ANDROID_API_MIN`](../prop_tgt/android_api_min#prop_tgt:ANDROID_API_MIN "ANDROID_API_MIN") target property. See that target property for additional information.
cmake CMAKE_CACHEFILE_DIR CMAKE\_CACHEFILE\_DIR
=====================
The directory with the `CMakeCache.txt` file.
This is the full path to the directory that has the `CMakeCache.txt` file in it. This is the same as [`CMAKE_BINARY_DIR`](cmake_binary_dir#variable:CMAKE_BINARY_DIR "CMAKE_BINARY_DIR").
cmake CTEST_CUSTOM_POST_MEMCHECK CTEST\_CUSTOM\_POST\_MEMCHECK
=============================
A list of commands to run at the end of the [`ctest_memcheck()`](../command/ctest_memcheck#command:ctest_memcheck "ctest_memcheck") command.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CMAKE_ANDROID_PROCESS_MAX CMAKE\_ANDROID\_PROCESS\_MAX
============================
Default value for the [`ANDROID_PROCESS_MAX`](../prop_tgt/android_process_max#prop_tgt:ANDROID_PROCESS_MAX "ANDROID_PROCESS_MAX") target property. See that target property for additional information.
cmake CMAKE_IMPORT_LIBRARY_PREFIX CMAKE\_IMPORT\_LIBRARY\_PREFIX
==============================
The prefix for import libraries that you link to.
The prefix to use for the name of an import library if used on this platform.
`CMAKE_IMPORT_LIBRARY_PREFIX_<LANG>` overrides this for language `<LANG>`.
cmake CMAKE_HOST_SYSTEM_VERSION CMAKE\_HOST\_SYSTEM\_VERSION
============================
The OS version CMake is running on.
A numeric version string for the system. On systems that support `uname`, this variable is set to the output of `uname -r`. On other systems this is set to major-minor version numbers.
cmake CMAKE_CURRENT_LIST_LINE CMAKE\_CURRENT\_LIST\_LINE
==========================
The line number of the current file being processed.
This is the line number of the file currently being processed by cmake.
cmake CMAKE_SYSTEM_PROCESSOR CMAKE\_SYSTEM\_PROCESSOR
========================
The name of the CPU CMake is building for.
This variable is the same as [`CMAKE_HOST_SYSTEM_PROCESSOR`](cmake_host_system_processor#variable:CMAKE_HOST_SYSTEM_PROCESSOR "CMAKE_HOST_SYSTEM_PROCESSOR") if you build for the host system instead of the target system when cross compiling.
* The [`Green Hills MULTI`](https://cmake.org/cmake/help/v3.9/generator/Green%20Hills%20MULTI.html#generator:Green%20Hills%20MULTI "Green Hills MULTI") generator sets this to `ARM` by default.
cmake ENV ENV
===
Access environment variables.
Use the syntax `$ENV{VAR}` to read environment variable `VAR`. See also the [`set()`](../command/set#command:set "set") command to set `ENV{VAR}`.
cmake CTEST_USE_LAUNCHERS CTEST\_USE\_LAUNCHERS
=====================
Specify the CTest `UseLaunchers` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_RUNTIME_OUTPUT_DIRECTORY CMAKE\_RUNTIME\_OUTPUT\_DIRECTORY
=================================
Where to put all the [RUNTIME](../manual/cmake-buildsystem.7#runtime-output-artifacts) target files when built.
This variable is used to initialize the [`RUNTIME_OUTPUT_DIRECTORY`](../prop_tgt/runtime_output_directory#prop_tgt:RUNTIME_OUTPUT_DIRECTORY "RUNTIME_OUTPUT_DIRECTORY") property on all the targets. See that target property for additional information.
cmake CMAKE_CACHE_MINOR_VERSION CMAKE\_CACHE\_MINOR\_VERSION
============================
Minor version of CMake used to create the `CMakeCache.txt` file
This stores the minor version of CMake used to write a CMake cache file. It is only different when a different version of CMake is run on a previously created cache file.
cmake CMAKE_<LANG>_STANDARD_LIBRARIES CMAKE\_<LANG>\_STANDARD\_LIBRARIES
==================================
Libraries linked into every executable and shared library linked for language `<LANG>`. This is meant for specification of system libraries needed by the language for the current platform.
This variable should not be set by project code. It is meant to be set by CMake’s platform information modules for the current toolchain, or by a toolchain file when used with [`CMAKE_TOOLCHAIN_FILE`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE").
See also [`CMAKE_<LANG>_STANDARD_INCLUDE_DIRECTORIES`](# "CMAKE_<LANG>_STANDARD_INCLUDE_DIRECTORIES").
cmake CMAKE_TRY_COMPILE_CONFIGURATION CMAKE\_TRY\_COMPILE\_CONFIGURATION
==================================
Build configuration used for [`try_compile()`](../command/try_compile#command:try_compile "try_compile") and [`try_run()`](../command/try_run#command:try_run "try_run") projects.
Projects built by [`try_compile()`](../command/try_compile#command:try_compile "try_compile") and [`try_run()`](../command/try_run#command:try_run "try_run") are built synchronously during the CMake configuration step. Therefore a specific build configuration must be chosen even if the generated build system supports multiple configurations.
cmake CTEST_CVS_CHECKOUT CTEST\_CVS\_CHECKOUT
====================
Deprecated. Use [`CTEST_CHECKOUT_COMMAND`](ctest_checkout_command#variable:CTEST_CHECKOUT_COMMAND "CTEST_CHECKOUT_COMMAND") instead.
cmake CTEST_GIT_UPDATE_CUSTOM CTEST\_GIT\_UPDATE\_CUSTOM
==========================
Specify the CTest `GITUpdateCustom` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_<LANG>_COMPILER_TARGET CMAKE\_<LANG>\_COMPILER\_TARGET
===============================
The target for cross-compiling, if supported.
Some compiler drivers are inherently cross-compilers, such as clang and QNX qcc. These compiler drivers support a command-line argument to specify the target to cross-compile for.
This variable may only be set in a toolchain file specified by the [`CMAKE_TOOLCHAIN_FILE`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE") variable.
cmake <PROJECT-NAME>_SOURCE_DIR <PROJECT-NAME>\_SOURCE\_DIR
===========================
Top level source directory for the named project.
A variable is created with the name used in the [`project()`](../command/project#command:project "project") command, and is the source directory for the project. This can be useful when [`add_subdirectory()`](../command/add_subdirectory#command:add_subdirectory "add_subdirectory") is used to connect several projects.
cmake CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX CMAKE\_<LANG>\_ANDROID\_TOOLCHAIN\_PREFIX
=========================================
When [Cross Compiling for Android](../manual/cmake-toolchains.7#cross-compiling-for-android) this variable contains the absolute path prefixing the toolchain GNU compiler and its binutils.
See also [`CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX`](# "CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX") and [`CMAKE_<LANG>_ANDROID_TOOLCHAIN_MACHINE`](# "CMAKE_<LANG>_ANDROID_TOOLCHAIN_MACHINE").
For example, the path to the linker is:
```
${CMAKE_CXX_ANDROID_TOOLCHAIN_PREFIX}ld${CMAKE_CXX_ANDROID_TOOLCHAIN_SUFFIX}
```
cmake CTEST_EXTRA_COVERAGE_GLOB CTEST\_EXTRA\_COVERAGE\_GLOB
============================
A list of regular expressions which will be used to find files which should be covered by the [`ctest_coverage()`](../command/ctest_coverage#command:ctest_coverage "ctest_coverage") command.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CMAKE_AUTOMOC_DEPEND_FILTERS CMAKE\_AUTOMOC\_DEPEND\_FILTERS
===============================
Filter definitions used by [`CMAKE_AUTOMOC`](cmake_automoc#variable:CMAKE_AUTOMOC "CMAKE_AUTOMOC") to extract file names from source code as additional dependencies for the `moc` file.
This variable is used to initialize the [`AUTOMOC_DEPEND_FILTERS`](../prop_tgt/automoc_depend_filters#prop_tgt:AUTOMOC_DEPEND_FILTERS "AUTOMOC_DEPEND_FILTERS") property on all the targets. See that target property for additional information.
By default it is empty.
cmake CMAKE_<LANG>_GHS_KERNEL_FLAGS_MINSIZEREL CMAKE\_<LANG>\_GHS\_KERNEL\_FLAGS\_MINSIZEREL
=============================================
GHS kernel flags for `MinSizeRel` build type or configuration.
`<LANG>` flags used when [`CMAKE_BUILD_TYPE`](cmake_build_type#variable:CMAKE_BUILD_TYPE "CMAKE_BUILD_TYPE") is `MinSizeRel` (short for minimum size release).
cmake CMAKE_STATIC_LINKER_FLAGS CMAKE\_STATIC\_LINKER\_FLAGS
============================
Linker flags to be used to create static libraries.
These flags will be used by the linker when creating a static library.
cmake CMAKE_INSTALL_RPATH CMAKE\_INSTALL\_RPATH
=====================
The rpath to use for installed targets.
A semicolon-separated list specifying the rpath to use in installed targets (for platforms that support it). This is used to initialize the target property [`INSTALL_RPATH`](../prop_tgt/install_rpath#prop_tgt:INSTALL_RPATH "INSTALL_RPATH") for all targets.
cmake CMAKE_LINK_DEF_FILE_FLAG CMAKE\_LINK\_DEF\_FILE\_FLAG
============================
Linker flag to be used to specify a `.def` file for dll creation.
The flag will be used to add a `.def` file when creating a dll on Windows; this is only defined on Windows.
cmake CMAKE_<LANG>_FLAGS_RELWITHDEBINFO_INIT CMAKE\_<LANG>\_FLAGS\_RELWITHDEBINFO\_INIT
==========================================
Value used to initialize the [`CMAKE_<LANG>_FLAGS_RELWITHDEBINFO`](# "CMAKE_<LANG>_FLAGS_RELWITHDEBINFO") cache entry the first time a build tree is configured for language `<LANG>`. This variable is meant to be set by a [`toolchain file`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE"). CMake may prepend or append content to the value based on the environment and target platform.
See also [`CMAKE_<LANG>_FLAGS_INIT`](# "CMAKE_<LANG>_FLAGS_INIT").
cmake CMAKE_<LANG>_ARCHIVE_CREATE CMAKE\_<LANG>\_ARCHIVE\_CREATE
==============================
Rule variable to create a new static archive.
This is a rule variable that tells CMake how to create a static archive. It is used in place of [`CMAKE_<LANG>_CREATE_STATIC_LIBRARY`](# "CMAKE_<LANG>_CREATE_STATIC_LIBRARY") on some platforms in order to support large object counts. See also [`CMAKE_<LANG>_ARCHIVE_APPEND`](# "CMAKE_<LANG>_ARCHIVE_APPEND") and [`CMAKE_<LANG>_ARCHIVE_FINISH`](# "CMAKE_<LANG>_ARCHIVE_FINISH").
cmake <PROJECT-NAME>_VERSION_MINOR <PROJECT-NAME>\_VERSION\_MINOR
==============================
Second version number component of the [`<PROJECT-NAME>_VERSION`](# "<PROJECT-NAME>_VERSION") variable as set by the [`project()`](../command/project#command:project "project") command.
cmake CMAKE_<LANG>_COMPILER CMAKE\_<LANG>\_COMPILER
=======================
The full path to the compiler for `LANG`.
This is the command that will be used as the `<LANG>` compiler. Once set, you can not change this variable.
cmake CMAKE_PROGRAM_PATH CMAKE\_PROGRAM\_PATH
====================
[;-list](../manual/cmake-language.7#cmake-language-lists) of directories specifying a search path for the [`find_program()`](../command/find_program#command:find_program "find_program") command. By default it is empty, it is intended to be set by the project. See also [`CMAKE_SYSTEM_PROGRAM_PATH`](cmake_system_program_path#variable:CMAKE_SYSTEM_PROGRAM_PATH "CMAKE_SYSTEM_PROGRAM_PATH") and [`CMAKE_PREFIX_PATH`](cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH").
cmake MSVC10 MSVC10
======
Discouraged. Use the [`MSVC_VERSION`](msvc_version#variable:MSVC_VERSION "MSVC_VERSION") variable instead.
`True` when using the Microsoft Visual Studio `v100` toolset (`cl` version 16) or another compiler that simulates it.
cmake CMAKE_LINK_SEARCH_END_STATIC CMAKE\_LINK\_SEARCH\_END\_STATIC
================================
End a link line such that static system libraries are used.
Some linkers support switches such as `-Bstatic` and `-Bdynamic` to determine whether to use static or shared libraries for `-lXXX` options. CMake uses these options to set the link type for libraries whose full paths are not known or (in some cases) are in implicit link directories for the platform. By default CMake adds an option at the end of the library list (if necessary) to set the linker search type back to its starting type. This property switches the final linker search type to `-Bstatic` regardless of how it started.
This variable is used to initialize the target property [`LINK_SEARCH_END_STATIC`](../prop_tgt/link_search_end_static#prop_tgt:LINK_SEARCH_END_STATIC "LINK_SEARCH_END_STATIC") for all targets. If set, it’s value is also used by the [`try_compile()`](../command/try_compile#command:try_compile "try_compile") command.
See also [`CMAKE_LINK_SEARCH_START_STATIC`](cmake_link_search_start_static#variable:CMAKE_LINK_SEARCH_START_STATIC "CMAKE_LINK_SEARCH_START_STATIC").
cmake CTEST_P4_UPDATE_OPTIONS CTEST\_P4\_UPDATE\_OPTIONS
==========================
Specify the CTest `P4UpdateOptions` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_SKIP_INSTALL_RPATH CMAKE\_SKIP\_INSTALL\_RPATH
===========================
Do not include RPATHs in the install tree.
Normally CMake uses the build tree for the RPATH when building executables etc on systems that use RPATH. When the software is installed the executables etc are relinked by CMake to have the install RPATH. If this variable is set to true then the software is always installed without RPATH, even if RPATH is enabled when building. This can be useful for example to allow running tests from the build directory with RPATH enabled before the installation step. To omit RPATH in both the build and install steps, use [`CMAKE_SKIP_RPATH`](cmake_skip_rpath#variable:CMAKE_SKIP_RPATH "CMAKE_SKIP_RPATH") instead.
cmake CPACK_INCLUDE_TOPLEVEL_DIRECTORY CPACK\_INCLUDE\_TOPLEVEL\_DIRECTORY
===================================
Boolean toggle to include/exclude top level directory.
When preparing a package CPack installs the item under the so-called top level directory. The purpose of is to include (set to `1` or `ON` or `TRUE`) the top level directory in the package or not (set to `0` or `OFF` or `FALSE`).
Each CPack generator has a built-in default value for this variable. E.g. Archive generators (ZIP, TGZ, …) includes the top level whereas RPM or DEB don’t. The user may override the default value by setting this variable.
There is a similar variable [`CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY`](cpack_component_include_toplevel_directory#variable:CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY "CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY") which may be used to override the behavior for the component packaging case which may have different default value for historical (now backward compatibility) reason.
cmake CMAKE_SHARED_LINKER_FLAGS_<CONFIG>_INIT CMAKE\_SHARED\_LINKER\_FLAGS\_<CONFIG>\_INIT
============================================
Value used to initialize the [`CMAKE_SHARED_LINKER_FLAGS_<CONFIG>`](# "CMAKE_SHARED_LINKER_FLAGS_<CONFIG>") cache entry the first time a build tree is configured. This variable is meant to be set by a [`toolchain file`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE"). CMake may prepend or append content to the value based on the environment and target platform.
See also [`CMAKE_SHARED_LINKER_FLAGS_INIT`](cmake_shared_linker_flags_init#variable:CMAKE_SHARED_LINKER_FLAGS_INIT "CMAKE_SHARED_LINKER_FLAGS_INIT").
cmake CTEST_HG_UPDATE_OPTIONS CTEST\_HG\_UPDATE\_OPTIONS
==========================
Specify the CTest `HGUpdateOptions` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_ARGC CMAKE\_ARGC
===========
Number of command line arguments passed to CMake in script mode.
When run in [-P](../manual/cmake.1#cmake-options) script mode, CMake sets this variable to the number of command line arguments. See also [`CMAKE_ARGV0`](cmake_argv0#variable:CMAKE_ARGV0 "CMAKE_ARGV0"), `1`, `2` …
cmake CMAKE_<LANG>_FLAGS_DEBUG_INIT CMAKE\_<LANG>\_FLAGS\_DEBUG\_INIT
=================================
Value used to initialize the [`CMAKE_<LANG>_FLAGS_DEBUG`](# "CMAKE_<LANG>_FLAGS_DEBUG") cache entry the first time a build tree is configured for language `<LANG>`. This variable is meant to be set by a [`toolchain file`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE"). CMake may prepend or append content to the value based on the environment and target platform.
See also [`CMAKE_<LANG>_FLAGS_INIT`](# "CMAKE_<LANG>_FLAGS_INIT").
cmake CMAKE_<LANG>_INCLUDE_WHAT_YOU_USE CMAKE\_<LANG>\_INCLUDE\_WHAT\_YOU\_USE
======================================
Default value for [`<LANG>_INCLUDE_WHAT_YOU_USE`](# "<LANG>_INCLUDE_WHAT_YOU_USE") target property. This variable is used to initialize the property on each target as it is created. This is done only when `<LANG>` is `C` or `CXX`.
cmake CMAKE_<CONFIG>_POSTFIX CMAKE\_<CONFIG>\_POSTFIX
========================
Default filename postfix for libraries under configuration `<CONFIG>`.
When a non-executable target is created its [`<CONFIG>_POSTFIX`](# "<CONFIG>_POSTFIX") target property is initialized with the value of this variable if it is set.
cmake CTEST_CHANGE_ID CTEST\_CHANGE\_ID
=================
Specify the CTest `ChangeId` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
This setting allows CTest to pass arbitrary information about this build up to CDash. One use of this feature is to allow CDash to post comments on your pull request if anything goes wrong with your build.
cmake CTEST_GIT_UPDATE_OPTIONS CTEST\_GIT\_UPDATE\_OPTIONS
===========================
Specify the CTest `GITUpdateOptions` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_OSX_DEPLOYMENT_TARGET CMAKE\_OSX\_DEPLOYMENT\_TARGET
==============================
Specify the minimum version of OS X on which the target binaries are to be deployed. CMake uses this value for the `-mmacosx-version-min` flag and to help choose the default SDK (see [`CMAKE_OSX_SYSROOT`](cmake_osx_sysroot#variable:CMAKE_OSX_SYSROOT "CMAKE_OSX_SYSROOT")).
If not set explicitly the value is initialized by the `MACOSX_DEPLOYMENT_TARGET` environment variable, if set, and otherwise computed based on the host platform.
The value of this variable should be set prior to the first [`project()`](../command/project#command:project "project") or [`enable_language()`](../command/enable_language#command:enable_language "enable_language") command invocation because it may influence configuration of the toolchain and flags. It is intended to be set locally by the user creating a build tree.
This variable is ignored on platforms other than OS X.
cmake CMAKE_HOST_APPLE CMAKE\_HOST\_APPLE
==================
`True` for Apple OS X operating systems.
Set to `true` when the host system is Apple OS X.
cmake MSVC71 MSVC71
======
Discouraged. Use the [`MSVC_VERSION`](msvc_version#variable:MSVC_VERSION "MSVC_VERSION") variable instead.
`True` when using Microsoft Visual C++ 7.1.
Set to `true` when the compiler is version 7.1 of Microsoft Visual C++.
cmake CMAKE_CUDA_STANDARD_REQUIRED CMAKE\_CUDA\_STANDARD\_REQUIRED
===============================
Default value for [`CUDA_STANDARD_REQUIRED`](../prop_tgt/cuda_standard_required#prop_tgt:CUDA_STANDARD_REQUIRED "CUDA_STANDARD_REQUIRED") property of targets.
This variable is used to initialize the [`CUDA_STANDARD_REQUIRED`](../prop_tgt/cuda_standard_required#prop_tgt:CUDA_STANDARD_REQUIRED "CUDA_STANDARD_REQUIRED") property on all targets. See that target property for additional information.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
| programming_docs |
cmake CMAKE_XCODE_ATTRIBUTE_<an-attribute> CMAKE\_XCODE\_ATTRIBUTE\_<an-attribute>
=======================================
Set Xcode target attributes directly.
Tell the [`Xcode`](https://cmake.org/cmake/help/v3.9/generator/Xcode.html#generator:Xcode "Xcode") generator to set ‘<an-attribute>’ to a given value in the generated Xcode project. Ignored on other generators.
See the [`XCODE_ATTRIBUTE_<an-attribute>`](# "XCODE_ATTRIBUTE_<an-attribute>") target property to set attributes on a specific target.
Contents of `CMAKE_XCODE_ATTRIBUTE_<an-attribute>` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake CMAKE_INCLUDE_CURRENT_DIR CMAKE\_INCLUDE\_CURRENT\_DIR
============================
Automatically add the current source- and build directories to the include path.
If this variable is enabled, CMake automatically adds [`CMAKE_CURRENT_SOURCE_DIR`](cmake_current_source_dir#variable:CMAKE_CURRENT_SOURCE_DIR "CMAKE_CURRENT_SOURCE_DIR") and [`CMAKE_CURRENT_BINARY_DIR`](cmake_current_binary_dir#variable:CMAKE_CURRENT_BINARY_DIR "CMAKE_CURRENT_BINARY_DIR") to the include path for each directory. These additional include directories do not propagate down to subdirectories. This is useful mainly for out-of-source builds, where files generated into the build tree are included by files located in the source tree.
By default `CMAKE_INCLUDE_CURRENT_DIR` is `OFF`.
cmake CMAKE_INSTALL_NAME_DIR CMAKE\_INSTALL\_NAME\_DIR
=========================
OS X directory name for installed targets.
`CMAKE_INSTALL_NAME_DIR` is used to initialize the [`INSTALL_NAME_DIR`](../prop_tgt/install_name_dir#prop_tgt:INSTALL_NAME_DIR "INSTALL_NAME_DIR") property on all targets. See that target property for more information.
cmake CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE CTEST\_CUSTOM\_MAXIMUM\_PASSED\_TEST\_OUTPUT\_SIZE
==================================================
When saving a passing test’s output, this is the maximum size, in bytes, that will be collected by the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command. Defaults to 1024 (1 KiB).
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CTEST_CVS_COMMAND CTEST\_CVS\_COMMAND
===================
Specify the CTest `CVSCommand` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_MODULE_LINKER_FLAGS_<CONFIG> CMAKE\_MODULE\_LINKER\_FLAGS\_<CONFIG>
======================================
Flags to be used when linking a module.
Same as `CMAKE_C_FLAGS_*` but used by the linker when creating modules.
cmake CMAKE_C_STANDARD CMAKE\_C\_STANDARD
==================
Default value for [`C_STANDARD`](../prop_tgt/c_standard#prop_tgt:C_STANDARD "C_STANDARD") property of targets.
This variable is used to initialize the [`C_STANDARD`](../prop_tgt/c_standard#prop_tgt:C_STANDARD "C_STANDARD") property on all targets. See that target property for additional information.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
cmake CMAKE_Fortran_FORMAT CMAKE\_Fortran\_FORMAT
======================
Set to `FIXED` or `FREE` to indicate the Fortran source layout.
This variable is used to initialize the [`Fortran_FORMAT`](../prop_tgt/fortran_format#prop_tgt:Fortran_FORMAT "Fortran_FORMAT") property on all the targets. See that target property for additional information.
cmake CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG CMAKE\_ANDROID\_NDK\_TOOLCHAIN\_HOST\_TAG
=========================================
When [Cross Compiling for Android with the NDK](../manual/cmake-toolchains.7#cross-compiling-for-android-with-the-ndk), this variable provides the NDK’s “host tag” used to construct the path to prebuilt toolchains that run on the host.
cmake CMAKE_CXX_COMPILE_FEATURES CMAKE\_CXX\_COMPILE\_FEATURES
=============================
List of features known to the C++ compiler
These features are known to be available for use with the C++ compiler. This list is a subset of the features listed in the [`CMAKE_CXX_KNOWN_FEATURES`](../prop_gbl/cmake_cxx_known_features#prop_gbl:CMAKE_CXX_KNOWN_FEATURES "CMAKE_CXX_KNOWN_FEATURES") global property.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
cmake CTEST_DROP_SITE_PASSWORD CTEST\_DROP\_SITE\_PASSWORD
===========================
Specify the CTest `DropSitePassword` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_DEBUG_POSTFIX CMAKE\_DEBUG\_POSTFIX
=====================
See variable [`CMAKE_<CONFIG>_POSTFIX`](# "CMAKE_<CONFIG>_POSTFIX").
This variable is a special case of the more-general [`CMAKE_<CONFIG>_POSTFIX`](# "CMAKE_<CONFIG>_POSTFIX") variable for the `DEBUG` configuration.
cmake CMAKE_SHARED_MODULE_SUFFIX CMAKE\_SHARED\_MODULE\_SUFFIX
=============================
The suffix for shared libraries that you link to.
The suffix to use for the end of a loadable module filename on this platform
`CMAKE_SHARED_MODULE_SUFFIX_<LANG>` overrides this for language `<LANG>`.
cmake CTEST_P4_OPTIONS CTEST\_P4\_OPTIONS
==================
Specify the CTest `P4Options` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake <PROJECT-NAME>_VERSION_TWEAK <PROJECT-NAME>\_VERSION\_TWEAK
==============================
Fourth version number component of the [`<PROJECT-NAME>_VERSION`](# "<PROJECT-NAME>_VERSION") variable as set by the [`project()`](../command/project#command:project "project") command.
cmake CMAKE_USER_MAKE_RULES_OVERRIDE CMAKE\_USER\_MAKE\_RULES\_OVERRIDE
==================================
Specify a CMake file that overrides platform information.
CMake loads the specified file while enabling support for each language from either the [`project()`](../command/project#command:project "project") or [`enable_language()`](../command/enable_language#command:enable_language "enable_language") commands. It is loaded after CMake’s builtin compiler and platform information modules have been loaded but before the information is used. The file may set platform information variables to override CMake’s defaults.
This feature is intended for use only in overriding information variables that must be set before CMake builds its first test project to check that the compiler for a language works. It should not be used to load a file in cases that a normal [`include()`](../command/include#command:include "include") will work. Use it only as a last resort for behavior that cannot be achieved any other way. For example, one may set the [`CMAKE_C_FLAGS_INIT`](# "CMAKE_<LANG>_FLAGS_INIT") variable to change the default value used to initialize the [`CMAKE_C_FLAGS`](# "CMAKE_<LANG>_FLAGS") variable before it is cached. The override file should NOT be used to set anything that could be set after languages are enabled, such as variables like [`CMAKE_RUNTIME_OUTPUT_DIRECTORY`](cmake_runtime_output_directory#variable:CMAKE_RUNTIME_OUTPUT_DIRECTORY "CMAKE_RUNTIME_OUTPUT_DIRECTORY") that affect the placement of binaries. Information set in the file will be used for [`try_compile()`](../command/try_compile#command:try_compile "try_compile") and [`try_run()`](../command/try_run#command:try_run "try_run") builds too.
cmake CTEST_CVS_UPDATE_OPTIONS CTEST\_CVS\_UPDATE\_OPTIONS
===========================
Specify the CTest `CVSUpdateOptions` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_SKIP_INSTALL_RULES CMAKE\_SKIP\_INSTALL\_RULES
===========================
Whether to disable generation of installation rules.
If `TRUE`, cmake will neither generate installaton rules nor will it generate `cmake_install.cmake` files. This variable is `FALSE` by default.
cmake CMAKE_MODULE_LINKER_FLAGS_INIT CMAKE\_MODULE\_LINKER\_FLAGS\_INIT
==================================
Value used to initialize the [`CMAKE_MODULE_LINKER_FLAGS`](cmake_module_linker_flags#variable:CMAKE_MODULE_LINKER_FLAGS "CMAKE_MODULE_LINKER_FLAGS") cache entry the first time a build tree is configured. This variable is meant to be set by a [`toolchain file`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE"). CMake may prepend or append content to the value based on the environment and target platform.
See also the configuration-specific variable [`CMAKE_MODULE_LINKER_FLAGS_<CONFIG>_INIT`](# "CMAKE_MODULE_LINKER_FLAGS_<CONFIG>_INIT").
cmake CMAKE_ANDROID_API CMAKE\_ANDROID\_API
===================
When [Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio Edition](../manual/cmake-toolchains.7#cross-compiling-for-android-with-nvidia-nsight-tegra-visual-studio-edition), this variable may be set to specify the default value for the [`ANDROID_API`](../prop_tgt/android_api#prop_tgt:ANDROID_API "ANDROID_API") target property. See that target property for additional information.
Otherwise, when [Cross Compiling for Android](../manual/cmake-toolchains.7#cross-compiling-for-android), this variable provides the Android API version number targeted. This will be the same value as the [`CMAKE_SYSTEM_VERSION`](cmake_system_version#variable:CMAKE_SYSTEM_VERSION "CMAKE_SYSTEM_VERSION") variable for `Android` platforms.
cmake CTEST_CUSTOM_ERROR_MATCH CTEST\_CUSTOM\_ERROR\_MATCH
===========================
A list of regular expressions which will be used to detect error messages in build outputs by the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CTEST_SCP_COMMAND CTEST\_SCP\_COMMAND
===================
Specify the CTest `SCPCommand` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_<LANG>_SIMULATE_ID CMAKE\_<LANG>\_SIMULATE\_ID
===========================
Identification string of “simulated” compiler.
Some compilers simulate other compilers to serve as drop-in replacements. When CMake detects such a compiler it sets this variable to what would have been the [`CMAKE_<LANG>_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") for the simulated compiler.
cmake CMAKE_CURRENT_LIST_FILE CMAKE\_CURRENT\_LIST\_FILE
==========================
Full path to the listfile currently being processed.
As CMake processes the listfiles in your project this variable will always be set to the one currently being processed. The value has dynamic scope. When CMake starts processing commands in a source file it sets this variable to the location of the file. When CMake finishes processing commands from the file it restores the previous value. Therefore the value of the variable inside a macro or function is the file invoking the bottom-most entry on the call stack, not the file containing the macro or function definition.
See also [`CMAKE_PARENT_LIST_FILE`](cmake_parent_list_file#variable:CMAKE_PARENT_LIST_FILE "CMAKE_PARENT_LIST_FILE").
cmake CMAKE_HOST_UNIX CMAKE\_HOST\_UNIX
=================
`True` for UNIX and UNIX like operating systems.
Set to `true` when the host system is UNIX or UNIX like (i.e. APPLE and CYGWIN).
cmake CMAKE_PDB_OUTPUT_DIRECTORY_<CONFIG> CMAKE\_PDB\_OUTPUT\_DIRECTORY\_<CONFIG>
=======================================
Per-configuration output directory for MS debug symbol `.pdb` files generated by the linker for executable and shared library targets.
This is a per-configuration version of [`CMAKE_PDB_OUTPUT_DIRECTORY`](cmake_pdb_output_directory#variable:CMAKE_PDB_OUTPUT_DIRECTORY "CMAKE_PDB_OUTPUT_DIRECTORY"). This variable is used to initialize the [`PDB_OUTPUT_DIRECTORY_<CONFIG>`](# "PDB_OUTPUT_DIRECTORY_<CONFIG>") property on all the targets. See that target property for additional information.
cmake CMAKE_ANDROID_ASSETS_DIRECTORIES CMAKE\_ANDROID\_ASSETS\_DIRECTORIES
===================================
Default value for the [`ANDROID_ASSETS_DIRECTORIES`](../prop_tgt/android_assets_directories#prop_tgt:ANDROID_ASSETS_DIRECTORIES "ANDROID_ASSETS_DIRECTORIES") target property. See that target property for additional information.
cmake CMAKE_LIBRARY_ARCHITECTURE CMAKE\_LIBRARY\_ARCHITECTURE
============================
Target architecture library directory name, if detected.
This is the value of [`CMAKE_<LANG>_LIBRARY_ARCHITECTURE`](# "CMAKE_<LANG>_LIBRARY_ARCHITECTURE") as detected for one of the enabled languages.
cmake CMAKE_<LANG>_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES CMAKE\_<LANG>\_IMPLICIT\_LINK\_FRAMEWORK\_DIRECTORIES
=====================================================
Implicit linker framework search path detected for language `<LANG>`.
These paths are implicit linker framework search directories for the compiler’s language. CMake automatically detects these directories for each language and reports the results in this variable.
cmake CTEST_BZR_UPDATE_OPTIONS CTEST\_BZR\_UPDATE\_OPTIONS
===========================
Specify the CTest `BZRUpdateOptions` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_ANDROID_NATIVE_LIB_DIRECTORIES CMAKE\_ANDROID\_NATIVE\_LIB\_DIRECTORIES
========================================
Default value for the [`ANDROID_NATIVE_LIB_DIRECTORIES`](../prop_tgt/android_native_lib_directories#prop_tgt:ANDROID_NATIVE_LIB_DIRECTORIES "ANDROID_NATIVE_LIB_DIRECTORIES") target property. See that target property for additional information.
cmake CMAKE_RANLIB CMAKE\_RANLIB
=============
Name of randomizing tool for static libraries.
This specifies name of the program that randomizes libraries on UNIX, not used on Windows, but may be present.
cmake ANDROID ANDROID
=======
Set to `1` when the target system ([`CMAKE_SYSTEM_NAME`](cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME")) is `Android`.
cmake CMAKE_<LANG>_CLANG_TIDY CMAKE\_<LANG>\_CLANG\_TIDY
==========================
Default value for [`<LANG>_CLANG_TIDY`](# "<LANG>_CLANG_TIDY") target property. This variable is used to initialize the property on each target as it is created. This is done only when `<LANG>` is `C` or `CXX`.
cmake CMAKE_SYSTEM_FRAMEWORK_PATH CMAKE\_SYSTEM\_FRAMEWORK\_PATH
==============================
Search path for OS X frameworks used by the [`find_library()`](../command/find_library#command:find_library "find_library"), [`find_package()`](../command/find_package#command:find_package "find_package"), [`find_path()`](../command/find_path#command:find_path "find_path"), and [`find_file()`](../command/find_file#command:find_file "find_file") commands. By default it contains the standard directories for the current system. It is *not* intended to be modified by the project, use [`CMAKE_FRAMEWORK_PATH`](cmake_framework_path#variable:CMAKE_FRAMEWORK_PATH "CMAKE_FRAMEWORK_PATH") for this.
cmake CTEST_UPDATE_VERSION_ONLY CTEST\_UPDATE\_VERSION\_ONLY
============================
Specify the CTest `UpdateVersionOnly` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_SYSROOT_LINK CMAKE\_SYSROOT\_LINK
====================
Path to pass to the compiler in the `--sysroot` flag when linking. This is the same as [`CMAKE_SYSROOT`](cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") but is used only for linking and not compiling sources.
This variable may only be set in a toolchain file specified by the [`CMAKE_TOOLCHAIN_FILE`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE") variable.
cmake LIBRARY_OUTPUT_PATH LIBRARY\_OUTPUT\_PATH
=====================
Old library location variable.
The target properties [`ARCHIVE_OUTPUT_DIRECTORY`](../prop_tgt/archive_output_directory#prop_tgt:ARCHIVE_OUTPUT_DIRECTORY "ARCHIVE_OUTPUT_DIRECTORY"), [`LIBRARY_OUTPUT_DIRECTORY`](../prop_tgt/library_output_directory#prop_tgt:LIBRARY_OUTPUT_DIRECTORY "LIBRARY_OUTPUT_DIRECTORY"), and [`RUNTIME_OUTPUT_DIRECTORY`](../prop_tgt/runtime_output_directory#prop_tgt:RUNTIME_OUTPUT_DIRECTORY "RUNTIME_OUTPUT_DIRECTORY") supercede this variable for a target if they are set. Library targets are otherwise placed in this directory.
cmake CMAKE_CONFIGURATION_TYPES CMAKE\_CONFIGURATION\_TYPES
===========================
Specifies the available build types on multi-config generators.
This specifies what build types (configurations) will be available such as `Debug`, `Release`, `RelWithDebInfo` etc. This has reasonable defaults on most platforms, but can be extended to provide other build types. See also [`CMAKE_BUILD_TYPE`](cmake_build_type#variable:CMAKE_BUILD_TYPE "CMAKE_BUILD_TYPE") for details of managing configuration data, and [`CMAKE_CFG_INTDIR`](cmake_cfg_intdir#variable:CMAKE_CFG_INTDIR "CMAKE_CFG_INTDIR").
cmake BORLAND BORLAND
=======
`True` if the Borland compiler is being used.
This is set to `true` if the Borland compiler is being used.
cmake CPACK_PACKAGING_INSTALL_PREFIX CPACK\_PACKAGING\_INSTALL\_PREFIX
=================================
The prefix used in the built package.
Each CPack generator has a default value (like `/usr`). This default value may be overwritten from the `CMakeLists.txt` or the [`cpack(1)`](../manual/cpack.1#manual:cpack(1) "cpack(1)") command line by setting an alternative value. Example:
```
set(CPACK_PACKAGING_INSTALL_PREFIX "/opt")
```
This is not the same purpose as [`CMAKE_INSTALL_PREFIX`](cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") which is used when installing from the build tree without building a package.
cmake CMAKE_MAKE_PROGRAM CMAKE\_MAKE\_PROGRAM
====================
Tool that can launch the native build system. The value may be the full path to an executable or just the tool name if it is expected to be in the `PATH`.
The tool selected depends on the [`CMAKE_GENERATOR`](cmake_generator#variable:CMAKE_GENERATOR "CMAKE_GENERATOR") used to configure the project:
* The [Makefile Generators](../manual/cmake-generators.7#makefile-generators) set this to `make`, `gmake`, or a generator-specific tool (e.g. `nmake` for [`NMake Makefiles`](https://cmake.org/cmake/help/v3.9/generator/NMake%20Makefiles.html#generator:NMake%20Makefiles "NMake Makefiles")).
These generators store `CMAKE_MAKE_PROGRAM` in the CMake cache so that it may be edited by the user.
* The [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator sets this to `ninja`.
This generator stores `CMAKE_MAKE_PROGRAM` in the CMake cache so that it may be edited by the user.
* The [`Xcode`](https://cmake.org/cmake/help/v3.9/generator/Xcode.html#generator:Xcode "Xcode") generator sets this to `xcodebuild` (or possibly an otherwise undocumented `cmakexbuild` wrapper implementing some workarounds).
This generator prefers to lookup the build tool at build time rather than to store `CMAKE_MAKE_PROGRAM` in the CMake cache ahead of time. This is because `xcodebuild` is easy to find, the `cmakexbuild` wrapper is needed only for older Xcode versions, and the path to `cmakexbuild` may be outdated if CMake itself moves.
For compatibility with versions of CMake prior to 3.2, if a user or project explicitly adds `CMAKE_MAKE_PROGRAM` to the CMake cache then CMake will use the specified value.
* The [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators) set this to the full path to `MSBuild.exe` (VS >= 10), `devenv.com` (VS 7,8,9), or `VCExpress.exe` (VS Express 8,9). (See also variables [`CMAKE_VS_MSBUILD_COMMAND`](cmake_vs_msbuild_command#variable:CMAKE_VS_MSBUILD_COMMAND "CMAKE_VS_MSBUILD_COMMAND") and [`CMAKE_VS_DEVENV_COMMAND`](cmake_vs_devenv_command#variable:CMAKE_VS_DEVENV_COMMAND "CMAKE_VS_DEVENV_COMMAND").
These generators prefer to lookup the build tool at build time rather than to store `CMAKE_MAKE_PROGRAM` in the CMake cache ahead of time. This is because the tools are version-specific and can be located using the Windows Registry. It is also necessary because the proper build tool may depend on the project content (e.g. the Intel Fortran plugin to VS 10 and 11 requires `devenv.com` to build its `.vfproj` project files even though `MSBuild.exe` is normally preferred to support the [`CMAKE_GENERATOR_TOOLSET`](cmake_generator_toolset#variable:CMAKE_GENERATOR_TOOLSET "CMAKE_GENERATOR_TOOLSET")).
For compatibility with versions of CMake prior to 3.0, if a user or project explicitly adds `CMAKE_MAKE_PROGRAM` to the CMake cache then CMake will use the specified value if possible.
* The [`Green Hills MULTI`](https://cmake.org/cmake/help/v3.9/generator/Green%20Hills%20MULTI.html#generator:Green%20Hills%20MULTI "Green Hills MULTI") generator sets this to `gbuild`. If a user or project explicitly adds `CMAKE_MAKE_PROGRAM` to the CMake cache then CMake will use the specified value.
The `CMAKE_MAKE_PROGRAM` variable is set for use by project code. The value is also used by the [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") `--build` and [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") `--build-and-test` tools to launch the native build process.
| programming_docs |
cmake CMAKE_JOB_POOL_LINK CMAKE\_JOB\_POOL\_LINK
======================
This variable is used to initialize the [`JOB_POOL_LINK`](../prop_tgt/job_pool_link#prop_tgt:JOB_POOL_LINK "JOB_POOL_LINK") property on all the targets. See [`JOB_POOL_LINK`](../prop_tgt/job_pool_link#prop_tgt:JOB_POOL_LINK "JOB_POOL_LINK") for additional information.
cmake CMAKE_POLICY_DEFAULT_CMP<NNNN> CMAKE\_POLICY\_DEFAULT\_CMP<NNNN>
=================================
Default for CMake Policy `CMP<NNNN>` when it is otherwise left unset.
Commands [`cmake_minimum_required(VERSION)`](../command/cmake_minimum_required#command:cmake_minimum_required "cmake_minimum_required") and [`cmake_policy(VERSION)`](../command/cmake_policy#command:cmake_policy "cmake_policy") by default leave policies introduced after the given version unset. Set `CMAKE_POLICY_DEFAULT_CMP<NNNN>` to `OLD` or `NEW` to specify the default for policy `CMP<NNNN>`, where `<NNNN>` is the policy number.
This variable should not be set by a project in CMake code; use [`cmake_policy(SET)`](../command/cmake_policy#command:cmake_policy "cmake_policy") instead. Users running CMake may set this variable in the cache (e.g. `-DCMAKE_POLICY_DEFAULT_CMP<NNNN>=<OLD|NEW>`) to set a policy not otherwise set by the project. Set to `OLD` to quiet a policy warning while using old behavior or to `NEW` to try building the project with new behavior.
cmake CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY CMAKE\_FIND\_PACKAGE\_NO\_SYSTEM\_PACKAGE\_REGISTRY
===================================================
Skip [System Package Registry](../manual/cmake-packages.7#system-package-registry) in [`find_package()`](../command/find_package#command:find_package "find_package") calls.
In some cases, it is not desirable to use the [System Package Registry](../manual/cmake-packages.7#system-package-registry) when searching for packages. If the [`CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY`](#variable:CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY "CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY") variable is enabled, all the [`find_package()`](../command/find_package#command:find_package "find_package") commands will skip the [System Package Registry](../manual/cmake-packages.7#system-package-registry) as if they were called with the `NO_CMAKE_SYSTEM_PACKAGE_REGISTRY` argument.
See also [Disabling the Package Registry](../manual/cmake-packages.7#disabling-the-package-registry).
cmake CMAKE_COMPILER_IS_GNUCXX CMAKE\_COMPILER\_IS\_GNUCXX
===========================
True if the C++ (`CXX`) compiler is GNU. Use [`CMAKE_CXX_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") instead.
cmake CMAKE_<LANG>_SIZEOF_DATA_PTR CMAKE\_<LANG>\_SIZEOF\_DATA\_PTR
================================
Size of pointer-to-data types for language `<LANG>`.
This holds the size (in bytes) of pointer-to-data types in the target platform ABI. It is defined for languages `C` and `CXX` (C++).
cmake CMAKE_LINK_LIBRARY_FLAG CMAKE\_LINK\_LIBRARY\_FLAG
==========================
Flag to be used to link a library into an executable.
The flag will be used to specify a library to link to an executable. On most compilers this is `-l`.
cmake CMAKE_MODULE_PATH CMAKE\_MODULE\_PATH
===================
[;-list](../manual/cmake-language.7#cmake-language-lists) of directories specifying a search path for CMake modules to be loaded by the the [`include()`](../command/include#command:include "include") or [`find_package()`](../command/find_package#command:find_package "find_package") commands before checking the default modules that come with CMake. By default it is empty, it is intended to be set by the project.
cmake CMAKE_<LANG>_COMPILER_VERSION CMAKE\_<LANG>\_COMPILER\_VERSION
================================
Compiler version string.
Compiler version in major[.minor[.patch[.tweak]]] format. This variable is not guaranteed to be defined for all compilers or languages.
For example `CMAKE_C_COMPILER_VERSION` and `CMAKE_CXX_COMPILER_VERSION` might indicate the respective C and C++ compiler version.
cmake CMAKE_<LANG>_SIMULATE_VERSION CMAKE\_<LANG>\_SIMULATE\_VERSION
================================
Version string of “simulated” compiler.
Some compilers simulate other compilers to serve as drop-in replacements. When CMake detects such a compiler it sets this variable to what would have been the [`CMAKE_<LANG>_COMPILER_VERSION`](# "CMAKE_<LANG>_COMPILER_VERSION") for the simulated compiler.
cmake CTEST_CURL_OPTIONS CTEST\_CURL\_OPTIONS
====================
Specify the CTest `CurlOptions` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CTEST_SITE CTEST\_SITE
===========
Specify the CTest `Site` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_C_EXTENSIONS CMAKE\_C\_EXTENSIONS
====================
Default value for [`C_EXTENSIONS`](../prop_tgt/c_extensions#prop_tgt:C_EXTENSIONS "C_EXTENSIONS") property of targets.
This variable is used to initialize the [`C_EXTENSIONS`](../prop_tgt/c_extensions#prop_tgt:C_EXTENSIONS "C_EXTENSIONS") property on all targets. See that target property for additional information.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
cmake CMAKE_<LANG>_GHS_KERNEL_FLAGS_RELEASE CMAKE\_<LANG>\_GHS\_KERNEL\_FLAGS\_RELEASE
==========================================
GHS kernel flags for `Release` build type or configuration.
`<LANG>` flags used when [`CMAKE_BUILD_TYPE`](cmake_build_type#variable:CMAKE_BUILD_TYPE "CMAKE_BUILD_TYPE") is `Release`.
cmake CMAKE_CUDA_EXTENSIONS CMAKE\_CUDA\_EXTENSIONS
=======================
Default value for [`CUDA_EXTENSIONS`](../prop_tgt/cuda_extensions#prop_tgt:CUDA_EXTENSIONS "CUDA_EXTENSIONS") property of targets.
This variable is used to initialize the [`CUDA_EXTENSIONS`](../prop_tgt/cuda_extensions#prop_tgt:CUDA_EXTENSIONS "CUDA_EXTENSIONS") property on all targets. See that target property for additional information.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
cmake CMAKE_<LANG>_COMPILER_LOADED CMAKE\_<LANG>\_COMPILER\_LOADED
===============================
Defined to true if the language is enabled.
When language `<LANG>` is enabled by [`project()`](../command/project#command:project "project") or [`enable_language()`](../command/enable_language#command:enable_language "enable_language") this variable is defined to `1`.
cmake CMAKE_INTERNAL_PLATFORM_ABI CMAKE\_INTERNAL\_PLATFORM\_ABI
==============================
An internal variable subject to change.
This is used in determining the compiler ABI and is subject to change.
cmake CMAKE_LIBRARY_OUTPUT_DIRECTORY_<CONFIG> CMAKE\_LIBRARY\_OUTPUT\_DIRECTORY\_<CONFIG>
===========================================
Where to put all the [LIBRARY](../manual/cmake-buildsystem.7#library-output-artifacts) target files when built for a specific configuration.
This variable is used to initialize the [`LIBRARY_OUTPUT_DIRECTORY_<CONFIG>`](# "LIBRARY_OUTPUT_DIRECTORY_<CONFIG>") property on all the targets. See that target property for additional information.
cmake CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT CMAKE\_INSTALL\_PREFIX\_INITIALIZED\_TO\_DEFAULT
================================================
CMake sets this variable to a `TRUE` value when the [`CMAKE_INSTALL_PREFIX`](cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") has just been initialized to its default value, typically on the first run of CMake within a new build tree. This can be used by project code to change the default without overriding a user-provided value:
```
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "/my/default" CACHE PATH "..." FORCE)
endif()
```
cmake CMAKE_MAP_IMPORTED_CONFIG_<CONFIG> CMAKE\_MAP\_IMPORTED\_CONFIG\_<CONFIG>
======================================
Default value for [`MAP_IMPORTED_CONFIG_<CONFIG>`](# "MAP_IMPORTED_CONFIG_<CONFIG>") of targets.
This variable is used to initialize the [`MAP_IMPORTED_CONFIG_<CONFIG>`](# "MAP_IMPORTED_CONFIG_<CONFIG>") property on all the targets. See that target property for additional information.
cmake CMAKE_BUILD_WITH_INSTALL_RPATH CMAKE\_BUILD\_WITH\_INSTALL\_RPATH
==================================
Use the install path for the `RPATH`.
Normally CMake uses the build tree for the `RPATH` when building executables etc on systems that use `RPATH`. When the software is installed the executables etc are relinked by CMake to have the install `RPATH`. If this variable is set to true then the software is always built with the install path for the `RPATH` and does not need to be relinked when installed.
cmake WIN32 WIN32
=====
`True` on Windows systems, including Win64.
Set to `true` when the target system is Windows.
cmake CMAKE_<LANG>_STANDARD_INCLUDE_DIRECTORIES CMAKE\_<LANG>\_STANDARD\_INCLUDE\_DIRECTORIES
=============================================
Include directories to be used for every source file compiled with the `<LANG>` compiler. This is meant for specification of system include directories needed by the language for the current platform. The directories always appear at the end of the include path passed to the compiler.
This variable should not be set by project code. It is meant to be set by CMake’s platform information modules for the current toolchain, or by a toolchain file when used with [`CMAKE_TOOLCHAIN_FILE`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE").
See also [`CMAKE_<LANG>_STANDARD_LIBRARIES`](# "CMAKE_<LANG>_STANDARD_LIBRARIES").
cmake CMAKE_EXECUTABLE_SUFFIX CMAKE\_EXECUTABLE\_SUFFIX
=========================
The suffix for executables on this platform.
The suffix to use for the end of an executable filename if any, `.exe` on Windows.
`CMAKE_EXECUTABLE_SUFFIX_<LANG>` overrides this for language `<LANG>`.
cmake CMAKE_ANDROID_ARM_NEON CMAKE\_ANDROID\_ARM\_NEON
=========================
When [Cross Compiling for Android](../manual/cmake-toolchains.7#cross-compiling-for-android) and [`CMAKE_ANDROID_ARCH_ABI`](cmake_android_arch_abi#variable:CMAKE_ANDROID_ARCH_ABI "CMAKE_ANDROID_ARCH_ABI") is set to `armeabi-v7a` set `CMAKE_ANDROID_ARM_NEON` to `ON` to target ARM NEON devices.
cmake CMAKE_INSTALL_MESSAGE CMAKE\_INSTALL\_MESSAGE
=======================
Specify verbosity of installation script code generated by the [`install()`](../command/install#command:install "install") command (using the [`file(INSTALL)`](../command/file#command:file "file") command). For paths that are newly installed or updated, installation may print lines like:
```
-- Installing: /some/destination/path
```
For paths that are already up to date, installation may print lines like:
```
-- Up-to-date: /some/destination/path
```
The `CMAKE_INSTALL_MESSAGE` variable may be set to control which messages are printed:
`ALWAYS` Print both `Installing` and `Up-to-date` messages.
`LAZY` Print `Installing` but not `Up-to-date` messages.
`NEVER` Print neither `Installing` nor `Up-to-date` messages. Other values have undefined behavior and may not be diagnosed.
If this variable is not set, the default behavior is `ALWAYS`.
cmake PROJECT_VERSION_MAJOR PROJECT\_VERSION\_MAJOR
=======================
First version number component of the [`PROJECT_VERSION`](project_version#variable:PROJECT_VERSION "PROJECT_VERSION") variable as set by the [`project()`](../command/project#command:project "project") command.
cmake CMAKE_IOS_INSTALL_COMBINED CMAKE\_IOS\_INSTALL\_COMBINED
=============================
Default value for [`IOS_INSTALL_COMBINED`](../prop_tgt/ios_install_combined#prop_tgt:IOS_INSTALL_COMBINED "IOS_INSTALL_COMBINED") of targets.
This variable is used to initialize the [`IOS_INSTALL_COMBINED`](../prop_tgt/ios_install_combined#prop_tgt:IOS_INSTALL_COMBINED "IOS_INSTALL_COMBINED") property on all the targets. See that target property for additional information.
cmake CMAKE_Fortran_MODOUT_FLAG CMAKE\_Fortran\_MODOUT\_FLAG
============================
Fortran flag to enable module output.
Most Fortran compilers write `.mod` files out by default. For others, this stores the flag needed to enable module output.
cmake CMAKE_CACHE_MAJOR_VERSION CMAKE\_CACHE\_MAJOR\_VERSION
============================
Major version of CMake used to create the `CMakeCache.txt` file
This stores the major version of CMake used to write a CMake cache file. It is only different when a different version of CMake is run on a previously created cache file.
cmake CMAKE_<LANG>_FLAGS_RELEASE CMAKE\_<LANG>\_FLAGS\_RELEASE
=============================
Flags for `Release` build type or configuration.
`<LANG>` flags used when [`CMAKE_BUILD_TYPE`](cmake_build_type#variable:CMAKE_BUILD_TYPE "CMAKE_BUILD_TYPE") is `Release`.
cmake CTEST_CUSTOM_ERROR_POST_CONTEXT CTEST\_CUSTOM\_ERROR\_POST\_CONTEXT
===================================
The number of lines to include as context which follow an error message by the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command. The default is 10.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake MSVC60 MSVC60
======
Discouraged. Use the [`MSVC_VERSION`](msvc_version#variable:MSVC_VERSION "MSVC_VERSION") variable instead.
`True` when using Microsoft Visual C++ 6.0.
Set to `true` when the compiler is version 6.0 of Microsoft Visual C++.
cmake PROJECT_VERSION PROJECT\_VERSION
================
Value given to the `VERSION` option of the most recent call to the [`project()`](../command/project#command:project "project") command, if any.
See also the component-wise version variables [`PROJECT_VERSION_MAJOR`](project_version_major#variable:PROJECT_VERSION_MAJOR "PROJECT_VERSION_MAJOR"), [`PROJECT_VERSION_MINOR`](project_version_minor#variable:PROJECT_VERSION_MINOR "PROJECT_VERSION_MINOR"), [`PROJECT_VERSION_PATCH`](project_version_patch#variable:PROJECT_VERSION_PATCH "PROJECT_VERSION_PATCH"), and [`PROJECT_VERSION_TWEAK`](project_version_tweak#variable:PROJECT_VERSION_TWEAK "PROJECT_VERSION_TWEAK").
cmake <PROJECT-NAME>_VERSION_MAJOR <PROJECT-NAME>\_VERSION\_MAJOR
==============================
First version number component of the [`<PROJECT-NAME>_VERSION`](# "<PROJECT-NAME>_VERSION") variable as set by the [`project()`](../command/project#command:project "project") command.
cmake CMAKE_AR CMAKE\_AR
=========
Name of archiving tool for static libraries.
This specifies the name of the program that creates archive or static libraries.
cmake CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION CPACK\_ERROR\_ON\_ABSOLUTE\_INSTALL\_DESTINATION
================================================
Ask CPack to error out as soon as a file with absolute `INSTALL DESTINATION` is encountered.
The fatal error is emitted before the installation of the offending file takes place. Some CPack generators, like NSIS, enforce this internally. This variable triggers the definition of [`CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION`](cmake_error_on_absolute_install_destination#variable:CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION "CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION") when CPack runs.
cmake CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS CMAKE\_WINDOWS\_EXPORT\_ALL\_SYMBOLS
====================================
Default value for [`WINDOWS_EXPORT_ALL_SYMBOLS`](../prop_tgt/windows_export_all_symbols#prop_tgt:WINDOWS_EXPORT_ALL_SYMBOLS "WINDOWS_EXPORT_ALL_SYMBOLS") target property. This variable is used to initialize the property on each target as it is created.
cmake CMAKE_<LANG>_ARCHIVE_FINISH CMAKE\_<LANG>\_ARCHIVE\_FINISH
==============================
Rule variable to finish an existing static archive.
This is a rule variable that tells CMake how to finish a static archive. It is used in place of [`CMAKE_<LANG>_CREATE_STATIC_LIBRARY`](# "CMAKE_<LANG>_CREATE_STATIC_LIBRARY") on some platforms in order to support large object counts. See also [`CMAKE_<LANG>_ARCHIVE_CREATE`](# "CMAKE_<LANG>_ARCHIVE_CREATE") and [`CMAKE_<LANG>_ARCHIVE_APPEND`](# "CMAKE_<LANG>_ARCHIVE_APPEND").
cmake CTEST_CONFIGURATION_TYPE CTEST\_CONFIGURATION\_TYPE
==========================
Specify the CTest `DefaultCTestConfigurationType` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_SYSTEM CMAKE\_SYSTEM
=============
Composite name of operating system CMake is compiling for.
This variable is the composite of [`CMAKE_SYSTEM_NAME`](cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME") and [`CMAKE_SYSTEM_VERSION`](cmake_system_version#variable:CMAKE_SYSTEM_VERSION "CMAKE_SYSTEM_VERSION"), e.g. `${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_VERSION}`. If [`CMAKE_SYSTEM_VERSION`](cmake_system_version#variable:CMAKE_SYSTEM_VERSION "CMAKE_SYSTEM_VERSION") is not set, then this variable is the same as [`CMAKE_SYSTEM_NAME`](cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME").
cmake CMAKE_FIND_PACKAGE_WARN_NO_MODULE CMAKE\_FIND\_PACKAGE\_WARN\_NO\_MODULE
======================================
Tell [`find_package()`](../command/find_package#command:find_package "find_package") to warn if called without an explicit mode.
If [`find_package()`](../command/find_package#command:find_package "find_package") is called without an explicit mode option (`MODULE`, `CONFIG`, or `NO_MODULE`) and no `Find<pkg>.cmake` module is in [`CMAKE_MODULE_PATH`](cmake_module_path#variable:CMAKE_MODULE_PATH "CMAKE_MODULE_PATH") then CMake implicitly assumes that the caller intends to search for a package configuration file. If no package configuration file is found then the wording of the failure message must account for both the case that the package is really missing and the case that the project has a bug and failed to provide the intended Find module. If instead the caller specifies an explicit mode option then the failure message can be more specific.
Set `CMAKE_FIND_PACKAGE_WARN_NO_MODULE` to `TRUE` to tell [`find_package()`](../command/find_package#command:find_package "find_package") to warn when it implicitly assumes Config mode. This helps developers enforce use of an explicit mode in all calls to [`find_package()`](../command/find_package#command:find_package "find_package") within a project.
cmake CMAKE_VERBOSE_MAKEFILE CMAKE\_VERBOSE\_MAKEFILE
========================
Enable verbose output from Makefile builds.
This variable is a cache entry initialized (to `FALSE`) by the [`project()`](../command/project#command:project "project") command. Users may enable the option in their local build tree to get more verbose output from Makefile builds and show each command line as it is launched.
cmake CMAKE_STATIC_LIBRARY_PREFIX CMAKE\_STATIC\_LIBRARY\_PREFIX
==============================
The prefix for static libraries that you link to.
The prefix to use for the name of a static library, `lib` on UNIX.
`CMAKE_STATIC_LIBRARY_PREFIX_<LANG>` overrides this for language `<LANG>`.
cmake CMAKE_ROOT CMAKE\_ROOT
===========
Install directory for running cmake.
This is the install root for the running CMake and the `Modules` directory can be found here. This is commonly used in this format: `${CMAKE_ROOT}/Modules`
cmake CMAKE_ENABLE_EXPORTS CMAKE\_ENABLE\_EXPORTS
======================
Specify whether an executable exports symbols for loadable modules.
Normally an executable does not export any symbols because it is the final program. It is possible for an executable to export symbols to be used by loadable modules. When this property is set to true CMake will allow other targets to `link` to the executable with the [`TARGET_LINK_LIBRARIES()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command. On all platforms a target-level dependency on the executable is created for targets that link to it. For DLL platforms an import library will be created for the exported symbols and then used for linking. All Windows-based systems including Cygwin are DLL platforms. For non-DLL platforms that require all symbols to be resolved at link time, such as OS X, the module will `link` to the executable using a flag like `-bundle_loader`. For other non-DLL platforms the link rule is simply ignored since the dynamic loader will automatically bind symbols when the module is loaded.
This variable is used to initialize the target property [`ENABLE_EXPORTS`](../prop_tgt/enable_exports#prop_tgt:ENABLE_EXPORTS "ENABLE_EXPORTS") for executable targets.
| programming_docs |
cmake PROJECT_SOURCE_DIR PROJECT\_SOURCE\_DIR
====================
Top level source directory for the current project.
This is the source directory of the most recent [`project()`](../command/project#command:project "project") command.
cmake CTEST_SVN_COMMAND CTEST\_SVN\_COMMAND
===================
Specify the CTest `SVNCommand` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_WARN_DEPRECATED CMAKE\_WARN\_DEPRECATED
=======================
Whether to issue warnings for deprecated functionality.
If not `FALSE`, use of deprecated functionality will issue warnings. If this variable is not set, CMake behaves as if it were set to `TRUE`.
When running [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)"), this option can be enabled with the `-Wdeprecated` option, or disabled with the `-Wno-deprecated` option.
cmake CMAKE_BUILD_TYPE CMAKE\_BUILD\_TYPE
==================
Specifies the build type on single-configuration generators.
This statically specifies what build type (configuration) will be built in this build tree. Possible values are empty, `Debug`, `Release`, `RelWithDebInfo` and `MinSizeRel`. This variable is only meaningful to single-configuration generators (such as [Makefile Generators](../manual/cmake-generators.7#makefile-generators) and [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja")) i.e. those which choose a single configuration when CMake runs to generate a build tree as opposed to multi-configuration generators which offer selection of the build configuration within the generated build environment. There are many per-config properties and variables (usually following clean `SOME_VAR_<CONFIG>` order conventions), such as `CMAKE_C_FLAGS_<CONFIG>`, specified as uppercase: `CMAKE_C_FLAGS_[DEBUG|RELEASE|RELWITHDEBINFO|MINSIZEREL]`. For example, in a build tree configured to build type `Debug`, CMake will see to having [`CMAKE_C_FLAGS_DEBUG`](# "CMAKE_<LANG>_FLAGS_DEBUG") settings get added to the [`CMAKE_C_FLAGS`](# "CMAKE_<LANG>_FLAGS") settings. See also [`CMAKE_CONFIGURATION_TYPES`](cmake_configuration_types#variable:CMAKE_CONFIGURATION_TYPES "CMAKE_CONFIGURATION_TYPES").
cmake CTEST_CUSTOM_WARNING_MATCH CTEST\_CUSTOM\_WARNING\_MATCH
=============================
A list of regular expressions which will be used to detect warning messages in build outputs by the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES CMAKE\_<LANG>\_IMPLICIT\_INCLUDE\_DIRECTORIES
=============================================
Directories implicitly searched by the compiler for header files.
CMake does not explicitly specify these directories on compiler command lines for language `<LANG>`. This prevents system include directories from being treated as user include directories on some compilers.
cmake CMAKE_ANDROID_JAR_DIRECTORIES CMAKE\_ANDROID\_JAR\_DIRECTORIES
================================
Default value for the [`ANDROID_JAR_DIRECTORIES`](../prop_tgt/android_jar_directories#prop_tgt:ANDROID_JAR_DIRECTORIES "ANDROID_JAR_DIRECTORIES") target property. See that target property for additional information.
cmake CMAKE_SYSTEM_PROGRAM_PATH CMAKE\_SYSTEM\_PROGRAM\_PATH
============================
[;-list](../manual/cmake-language.7#cmake-language-lists) of directories specifying a search path for the [`find_program()`](../command/find_program#command:find_program "find_program") command. By default this contains the standard directories for the current system. It is *not* intended to be modified by the project; use [`CMAKE_PROGRAM_PATH`](cmake_program_path#variable:CMAKE_PROGRAM_PATH "CMAKE_PROGRAM_PATH") for this. See also [`CMAKE_SYSTEM_PREFIX_PATH`](cmake_system_prefix_path#variable:CMAKE_SYSTEM_PREFIX_PATH "CMAKE_SYSTEM_PREFIX_PATH").
cmake CTEST_CUSTOM_MAXIMUM_NUMBER_OF_ERRORS CTEST\_CUSTOM\_MAXIMUM\_NUMBER\_OF\_ERRORS
==========================================
The maximum number of errors in a single build step which will be detected. After this, the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command will truncate the output. Defaults to 50.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CMAKE_ANDROID_SKIP_ANT_STEP CMAKE\_ANDROID\_SKIP\_ANT\_STEP
===============================
Default value for the [`ANDROID_SKIP_ANT_STEP`](../prop_tgt/android_skip_ant_step#prop_tgt:ANDROID_SKIP_ANT_STEP "ANDROID_SKIP_ANT_STEP") target property. See that target property for additional information.
cmake CMAKE_OSX_ARCHITECTURES CMAKE\_OSX\_ARCHITECTURES
=========================
Target specific architectures for OS X and iOS.
This variable is used to initialize the [`OSX_ARCHITECTURES`](../prop_tgt/osx_architectures#prop_tgt:OSX_ARCHITECTURES "OSX_ARCHITECTURES") property on each target as it is creaed. See that target property for additional information.
The value of this variable should be set prior to the first [`project()`](../command/project#command:project "project") or [`enable_language()`](../command/enable_language#command:enable_language "enable_language") command invocation because it may influence configuration of the toolchain and flags. It is intended to be set locally by the user creating a build tree.
This variable is ignored on platforms other than OS X.
cmake BUILD_SHARED_LIBS BUILD\_SHARED\_LIBS
===================
Global flag to cause [`add_library()`](../command/add_library#command:add_library "add_library") to create shared libraries if on.
If present and true, this will cause all libraries to be built shared unless the library was explicitly added as a static library. This variable is often added to projects as an [`option()`](../command/option#command:option "option") so that each user of a project can decide if they want to build the project using shared or static libraries.
cmake CMAKE_POSITION_INDEPENDENT_CODE CMAKE\_POSITION\_INDEPENDENT\_CODE
==================================
Default value for [`POSITION_INDEPENDENT_CODE`](../prop_tgt/position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE") of targets.
This variable is used to initialize the [`POSITION_INDEPENDENT_CODE`](../prop_tgt/position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE") property on all the targets. See that target property for additional information. If set, it’s value is also used by the [`try_compile()`](../command/try_compile#command:try_compile "try_compile") command.
cmake CTEST_MEMORYCHECK_COMMAND_OPTIONS CTEST\_MEMORYCHECK\_COMMAND\_OPTIONS
====================================
Specify the CTest `MemoryCheckCommandOptions` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_DISABLE_FIND_PACKAGE_<PackageName> CMAKE\_DISABLE\_FIND\_PACKAGE\_<PackageName>
============================================
Variable for disabling [`find_package()`](../command/find_package#command:find_package "find_package") calls.
Every non-`REQUIRED` [`find_package()`](../command/find_package#command:find_package "find_package") call in a project can be disabled by setting the variable `CMAKE_DISABLE_FIND_PACKAGE_<PackageName>` to `TRUE`. This can be used to build a project without an optional package, although that package is installed.
This switch should be used during the initial CMake run. Otherwise if the package has already been found in a previous CMake run, the variables which have been stored in the cache will still be there. In that case it is recommended to remove the cache variables for this package from the cache using the cache editor or [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") `-U`
cmake CTEST_NIGHTLY_START_TIME CTEST\_NIGHTLY\_START\_TIME
===========================
Specify the CTest `NightlyStartTime` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION CMAKE\_ANDROID\_NDK\_TOOLCHAIN\_VERSION
=======================================
When [Cross Compiling for Android with the NDK](../manual/cmake-toolchains.7#cross-compiling-for-android-with-the-ndk), this variable may be set to specify the version of the toolchain to be used as the compiler. The variable must be set to one of these forms:
* `<major>.<minor>`: GCC of specified version
* `clang<major>.<minor>`: Clang of specified version
* `clang`: Clang of most recent available version
A toolchain of the requested version will be selected automatically to match the ABI named in the [`CMAKE_ANDROID_ARCH_ABI`](cmake_android_arch_abi#variable:CMAKE_ANDROID_ARCH_ABI "CMAKE_ANDROID_ARCH_ABI") variable.
If not specified, the default will be a value that selects the latest available GCC toolchain.
cmake MSVC MSVC
====
`True` when using Microsoft Visual C++.
Set to `true` when the compiler is some version of Microsoft Visual C++.
See also the [`MSVC_VERSION`](msvc_version#variable:MSVC_VERSION "MSVC_VERSION") variable.
cmake CMAKE_SYSTEM_VERSION CMAKE\_SYSTEM\_VERSION
======================
The version of the operating system for which CMake is to build. See the [`CMAKE_SYSTEM_NAME`](cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME") variable for the OS name.
System Version for Host Builds
------------------------------
When the [`CMAKE_SYSTEM_NAME`](cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME") variable takes its default value then `CMAKE_SYSTEM_VERSION` is by default set to the same value as the [`CMAKE_HOST_SYSTEM_VERSION`](cmake_host_system_version#variable:CMAKE_HOST_SYSTEM_VERSION "CMAKE_HOST_SYSTEM_VERSION") variable so that the build targets the host system version.
In the case of a host build then `CMAKE_SYSTEM_VERSION` may be set explicitly when first configuring a new build tree in order to enable targeting the build for a different version of the host operating system than is actually running on the host. This is allowed and not considered cross compiling so long as the binaries built for the specified OS version can still run on the host.
System Version for Cross Compiling
----------------------------------
When the [`CMAKE_SYSTEM_NAME`](cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME") variable is set explicitly to enable [cross compiling](../manual/cmake-toolchains.7#cross-compiling-toolchain) then the value of `CMAKE_SYSTEM_VERSION` must also be set explicitly to specify the target system version.
cmake CMAKE_CURRENT_SOURCE_DIR CMAKE\_CURRENT\_SOURCE\_DIR
===========================
The path to the source directory currently being processed.
This the full path to the source directory that is currently being processed by cmake.
When run in -P script mode, CMake sets the variables [`CMAKE_BINARY_DIR`](cmake_binary_dir#variable:CMAKE_BINARY_DIR "CMAKE_BINARY_DIR"), [`CMAKE_SOURCE_DIR`](cmake_source_dir#variable:CMAKE_SOURCE_DIR "CMAKE_SOURCE_DIR"), [`CMAKE_CURRENT_BINARY_DIR`](cmake_current_binary_dir#variable:CMAKE_CURRENT_BINARY_DIR "CMAKE_CURRENT_BINARY_DIR") and [`CMAKE_CURRENT_SOURCE_DIR`](#variable:CMAKE_CURRENT_SOURCE_DIR "CMAKE_CURRENT_SOURCE_DIR") to the current working directory.
cmake CMAKE_<LANG>_GHS_KERNEL_FLAGS_RELWITHDEBINFO CMAKE\_<LANG>\_GHS\_KERNEL\_FLAGS\_RELWITHDEBINFO
=================================================
GHS kernel flags for `RelWithDebInfo` type or configuration.
`<LANG>` flags used when [`CMAKE_BUILD_TYPE`](cmake_build_type#variable:CMAKE_BUILD_TYPE "CMAKE_BUILD_TYPE") is `RelWithDebInfo` (short for Release With Debug Information).
cmake CMAKE_ABSOLUTE_DESTINATION_FILES CMAKE\_ABSOLUTE\_DESTINATION\_FILES
===================================
List of files which have been installed using an `ABSOLUTE DESTINATION` path.
This variable is defined by CMake-generated `cmake_install.cmake` scripts. It can be used (read-only) by programs or scripts that source those install scripts. This is used by some CPack generators (e.g. RPM).
cmake CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE CMAKE\_INCLUDE\_DIRECTORIES\_PROJECT\_BEFORE
============================================
Whether to force prepending of project include directories.
This variable affects the order of include directories generated in compiler command lines. If set to `ON`, it causes the [`CMAKE_SOURCE_DIR`](cmake_source_dir#variable:CMAKE_SOURCE_DIR "CMAKE_SOURCE_DIR") and the [`CMAKE_BINARY_DIR`](cmake_binary_dir#variable:CMAKE_BINARY_DIR "CMAKE_BINARY_DIR") to appear first.
cmake CMAKE_XCODE_GENERATE_SCHEME CMAKE\_XCODE\_GENERATE\_SCHEME
==============================
If enabled, the Xcode generator will generate schema files. Those are are useful to invoke analyze, archive, build-for-testing and test actions from the command line.
Note
The Xcode Schema Generator is still experimental and subject to change.
cmake CMAKE_<LANG>_LIBRARY_ARCHITECTURE CMAKE\_<LANG>\_LIBRARY\_ARCHITECTURE
====================================
Target architecture library directory name detected for `<LANG>`.
If the `<LANG>` compiler passes to the linker an architecture-specific system library search directory such as `<prefix>/lib/<arch>` this variable contains the `<arch>` name if/as detected by CMake.
cmake CMAKE_ANDROID_JAR_DEPENDENCIES CMAKE\_ANDROID\_JAR\_DEPENDENCIES
=================================
Default value for the [`ANDROID_JAR_DEPENDENCIES`](../prop_tgt/android_jar_dependencies#prop_tgt:ANDROID_JAR_DEPENDENCIES "ANDROID_JAR_DEPENDENCIES") target property. See that target property for additional information.
cmake CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS CTEST\_CUSTOM\_MAXIMUM\_NUMBER\_OF\_WARNINGS
============================================
The maximum number of warnings in a single build step which will be detected. After this, the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command will truncate the output. Defaults to 50.
It is initialized by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"), but may be edited in a `CTestCustom` file. See [`ctest_read_custom_files()`](../command/ctest_read_custom_files#command:ctest_read_custom_files "ctest_read_custom_files") documentation.
cmake CTEST_MEMORYCHECK_TYPE CTEST\_MEMORYCHECK\_TYPE
========================
Specify the CTest `MemoryCheckType` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script. Valid values are `Valgrind`, `Purify`, `BoundsChecker`, and `ThreadSanitizer`, `AddressSanitizer`, `LeakSanitizer`, `MemorySanitizer`, and `UndefinedBehaviorSanitizer`.
cmake CMAKE_ANDROID_GUI CMAKE\_ANDROID\_GUI
===================
Default value for the [`ANDROID_GUI`](../prop_tgt/android_gui#prop_tgt:ANDROID_GUI "ANDROID_GUI") target property of executables. See that target property for additional information.
cmake CMAKE_VISIBILITY_INLINES_HIDDEN CMAKE\_VISIBILITY\_INLINES\_HIDDEN
==================================
Default value for the [`VISIBILITY_INLINES_HIDDEN`](../prop_tgt/visibility_inlines_hidden#prop_tgt:VISIBILITY_INLINES_HIDDEN "VISIBILITY_INLINES_HIDDEN") target property when a target is created.
cmake CMAKE_FRAMEWORK_PATH CMAKE\_FRAMEWORK\_PATH
======================
[;-list](../manual/cmake-language.7#cmake-language-lists) of directories specifying a search path for OS X frameworks used by the [`find_library()`](../command/find_library#command:find_library "find_library"), [`find_package()`](../command/find_package#command:find_package "find_package"), [`find_path()`](../command/find_path#command:find_path "find_path"), and [`find_file()`](../command/find_file#command:find_file "find_file") commands.
cmake CMAKE_COMMAND CMAKE\_COMMAND
==============
The full path to the [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") executable.
This is the full path to the CMake executable [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") which is useful from custom commands that want to use the `cmake -E` option for portable system commands. (e.g. `/usr/local/bin/cmake`)
cmake CTEST_HG_COMMAND CTEST\_HG\_COMMAND
==================
Specify the CTest `HGCommand` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_STATIC_LINKER_FLAGS_INIT CMAKE\_STATIC\_LINKER\_FLAGS\_INIT
==================================
Value used to initialize the [`CMAKE_STATIC_LINKER_FLAGS`](cmake_static_linker_flags#variable:CMAKE_STATIC_LINKER_FLAGS "CMAKE_STATIC_LINKER_FLAGS") cache entry the first time a build tree is configured. This variable is meant to be set by a [`toolchain file`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE"). CMake may prepend or append content to the value based on the environment and target platform.
See also the configuration-specific variable [`CMAKE_STATIC_LINKER_FLAGS_<CONFIG>_INIT`](# "CMAKE_STATIC_LINKER_FLAGS_<CONFIG>_INIT").
cmake CMAKE_TRY_COMPILE_PLATFORM_VARIABLES CMAKE\_TRY\_COMPILE\_PLATFORM\_VARIABLES
========================================
List of variables that the [`try_compile()`](../command/try_compile#command:try_compile "try_compile") command source file signature must propagate into the test project in order to target the same platform as the host project.
This variable should not be set by project code. It is meant to be set by CMake’s platform information modules for the current toolchain, or by a toolchain file when used with [`CMAKE_TOOLCHAIN_FILE`](cmake_toolchain_file#variable:CMAKE_TOOLCHAIN_FILE "CMAKE_TOOLCHAIN_FILE").
Variables meaningful to CMake, such as [`CMAKE_<LANG>_FLAGS`](# "CMAKE_<LANG>_FLAGS"), are propagated automatically. The `CMAKE_TRY_COMPILE_PLATFORM_VARIABLES` variable may be set to pass custom variables meaningful to a toolchain file. For example, a toolchain file may contain:
```
set(CMAKE_SYSTEM_NAME ...)
set(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES MY_CUSTOM_VARIABLE)
# ... use MY_CUSTOM_VARIABLE ...
```
If a user passes `-DMY_CUSTOM_VARIABLE=SomeValue` to CMake then this setting will be made visible to the toolchain file both for the main project and for test projects generated by the [`try_compile()`](../command/try_compile#command:try_compile "try_compile") command source file signature.
cmake CMAKE_BUILD_WITH_INSTALL_NAME_DIR CMAKE\_BUILD\_WITH\_INSTALL\_NAME\_DIR
======================================
Whether to use [`INSTALL_NAME_DIR`](../prop_tgt/install_name_dir#prop_tgt:INSTALL_NAME_DIR "INSTALL_NAME_DIR") on targets in the build tree.
This variable is used to initialize the [`BUILD_WITH_INSTALL_NAME_DIR`](../prop_tgt/build_with_install_name_dir#prop_tgt:BUILD_WITH_INSTALL_NAME_DIR "BUILD_WITH_INSTALL_NAME_DIR") property on all targets.
cmake CPACK_INSTALL_SCRIPT CPACK\_INSTALL\_SCRIPT
======================
Extra CMake script provided by the user.
If set this CMake script will be executed by CPack during its local [CPack-private] installation which is done right before packaging the files. The script is not called by e.g.: `make install`.
cmake CMAKE_ANDROID_SECURE_PROPS_PATH CMAKE\_ANDROID\_SECURE\_PROPS\_PATH
===================================
Default value for the [`ANDROID_SECURE_PROPS_PATH`](../prop_tgt/android_secure_props_path#prop_tgt:ANDROID_SECURE_PROPS_PATH "ANDROID_SECURE_PROPS_PATH") target property. See that target property for additional information.
| programming_docs |
cmake CTEST_DROP_METHOD CTEST\_DROP\_METHOD
===================
Specify the CTest `DropMethod` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake WINDOWS_STORE WINDOWS\_STORE
==============
True when the [`CMAKE_SYSTEM_NAME`](cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME") variable is set to `WindowsStore`.
cmake CTEST_TEST_TIMEOUT CTEST\_TEST\_TIMEOUT
====================
Specify the CTest `TimeOut` setting in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_FIND_ROOT_PATH CMAKE\_FIND\_ROOT\_PATH
=======================
[;-list](../manual/cmake-language.7#cmake-language-lists) of root paths to search on the filesystem.
This variable is most useful when cross-compiling. CMake uses the paths in this list as alternative roots to find filesystem items with [`find_package()`](../command/find_package#command:find_package "find_package"), [`find_library()`](../command/find_library#command:find_library "find_library") etc.
cmake PROJECT_NAME PROJECT\_NAME
=============
Name of the project given to the project command.
This is the name given to the most recent [`project()`](../command/project#command:project "project") command.
cmake CMAKE_HOST_SYSTEM_NAME CMAKE\_HOST\_SYSTEM\_NAME
=========================
Name of the OS CMake is running on.
On systems that have the uname command, this variable is set to the output of `uname -s`. `Linux`, `Windows`, and `Darwin` for OS X are the values found on the big three operating systems.
cmake CTEST_CHECKOUT_COMMAND CTEST\_CHECKOUT\_COMMAND
========================
Tell the [`ctest_start()`](../command/ctest_start#command:ctest_start "ctest_start") command how to checkout or initialize the source directory in a [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") dashboard client script.
cmake CMAKE_SHARED_LINKER_FLAGS CMAKE\_SHARED\_LINKER\_FLAGS
============================
Linker flags to be used to create shared libraries.
These flags will be used by the linker when creating a shared library.
cmake CMAKE_MINIMUM_REQUIRED_VERSION CMAKE\_MINIMUM\_REQUIRED\_VERSION
=================================
Version specified to [`cmake_minimum_required()`](../command/cmake_minimum_required#command:cmake_minimum_required "cmake_minimum_required") command
Variable containing the `VERSION` component specified in the [`cmake_minimum_required()`](../command/cmake_minimum_required#command:cmake_minimum_required "cmake_minimum_required") command.
cmake CPackComponent CPackComponent
==============
Build binary and source package installers
Variables concerning CPack Components
-------------------------------------
The CPackComponent module is the module which handles the component part of CPack. See CPack module for general information about CPack.
For certain kinds of binary installers (including the graphical installers on Mac OS X and Windows), CPack generates installers that allow users to select individual application components to install. The contents of each of the components are identified by the COMPONENT argument of CMake’s INSTALL command. These components can be annotated with user-friendly names and descriptions, inter-component dependencies, etc., and grouped in various ways to customize the resulting installer. See the cpack\_add\_\* commands, described below, for more information about component-specific installations.
Component-specific installation allows users to select specific sets of components to install during the install process. Installation components are identified by the COMPONENT argument of CMake’s INSTALL commands, and should be further described by the following CPack commands:
`CPACK_COMPONENTS_ALL`
The list of component to install.
The default value of this variable is computed by CPack and contains all components defined by the project. The user may set it to only include the specified components.
`CPACK_<GENNAME>_COMPONENT_INSTALL`
Enable/Disable component install for CPack generator <GENNAME>.
Each CPack Generator (RPM, DEB, ARCHIVE, NSIS, DMG, etc…) has a legacy default behavior. e.g. RPM builds monolithic whereas NSIS builds component. One can change the default behavior by setting this variable to 0/1 or OFF/ON.
`CPACK_COMPONENTS_GROUPING`
Specify how components are grouped for multi-package component-aware CPack generators.
Some generators like RPM or ARCHIVE family (TGZ, ZIP, …) generates several packages files when asked for component packaging. They group the component differently depending on the value of this variable:
* ONE\_PER\_GROUP (default): creates one package file per component group
* ALL\_COMPONENTS\_IN\_ONE : creates a single package with all (requested) component
* IGNORE : creates one package per component, i.e. IGNORE component group
One can specify different grouping for different CPack generator by using a CPACK\_PROJECT\_CONFIG\_FILE.
`CPACK_COMPONENT_<compName>_DISPLAY_NAME`
The name to be displayed for a component.
`CPACK_COMPONENT_<compName>_DESCRIPTION`
The description of a component.
`CPACK_COMPONENT_<compName>_GROUP`
The group of a component.
`CPACK_COMPONENT_<compName>_DEPENDS`
The dependencies (list of components) on which this component depends.
`CPACK_COMPONENT_<compName>_HIDDEN`
True if this component is hidden from the user.
`CPACK_COMPONENT_<compName>_REQUIRED`
True if this component is required.
`CPACK_COMPONENT_<compName>_DISABLED`
True if this component is not selected to be installed by default.
`cpack_add_component`
Describes a CPack installation component named by the COMPONENT argument to a CMake INSTALL command.
```
cpack_add_component(compname
[DISPLAY_NAME name]
[DESCRIPTION description]
[HIDDEN | REQUIRED | DISABLED ]
[GROUP group]
[DEPENDS comp1 comp2 ... ]
[INSTALL_TYPES type1 type2 ... ]
[DOWNLOADED]
[ARCHIVE_FILE filename]
[PLIST filename])
```
The cmake\_add\_component command describes an installation component, which the user can opt to install or remove as part of the graphical installation process. compname is the name of the component, as provided to the COMPONENT argument of one or more CMake INSTALL commands.
DISPLAY\_NAME is the displayed name of the component, used in graphical installers to display the component name. This value can be any string.
DESCRIPTION is an extended description of the component, used in graphical installers to give the user additional information about the component. Descriptions can span multiple lines using `\n` as the line separator. Typically, these descriptions should be no more than a few lines long.
HIDDEN indicates that this component will be hidden in the graphical installer, so that the user cannot directly change whether it is installed or not.
REQUIRED indicates that this component is required, and therefore will always be installed. It will be visible in the graphical installer, but it cannot be unselected. (Typically, required components are shown greyed out).
DISABLED indicates that this component should be disabled (unselected) by default. The user is free to select this component for installation, unless it is also HIDDEN.
DEPENDS lists the components on which this component depends. If this component is selected, then each of the components listed must also be selected. The dependency information is encoded within the installer itself, so that users cannot install inconsistent sets of components.
GROUP names the component group of which this component is a part. If not provided, the component will be a standalone component, not part of any component group. Component groups are described with the cpack\_add\_component\_group command, detailed below.
INSTALL\_TYPES lists the installation types of which this component is a part. When one of these installations types is selected, this component will automatically be selected. Installation types are described with the cpack\_add\_install\_type command, detailed below.
DOWNLOADED indicates that this component should be downloaded on-the-fly by the installer, rather than packaged in with the installer itself. For more information, see the cpack\_configure\_downloads command.
ARCHIVE\_FILE provides a name for the archive file created by CPack to be used for downloaded components. If not supplied, CPack will create a file with some name based on CPACK\_PACKAGE\_FILE\_NAME and the name of the component. See cpack\_configure\_downloads for more information.
PLIST gives a filename that is passed to pkgbuild with the `--component-plist` argument when using the productbuild generator.
`cpack_add_component_group`
Describes a group of related CPack installation components.
```
cpack_add_component_group(groupname
[DISPLAY_NAME name]
[DESCRIPTION description]
[PARENT_GROUP parent]
[EXPANDED]
[BOLD_TITLE])
```
The cpack\_add\_component\_group describes a group of installation components, which will be placed together within the listing of options. Typically, component groups allow the user to select/deselect all of the components within a single group via a single group-level option. Use component groups to reduce the complexity of installers with many options. groupname is an arbitrary name used to identify the group in the GROUP argument of the cpack\_add\_component command, which is used to place a component in a group. The name of the group must not conflict with the name of any component.
DISPLAY\_NAME is the displayed name of the component group, used in graphical installers to display the component group name. This value can be any string.
DESCRIPTION is an extended description of the component group, used in graphical installers to give the user additional information about the components within that group. Descriptions can span multiple lines using `\n` as the line separator. Typically, these descriptions should be no more than a few lines long.
PARENT\_GROUP, if supplied, names the parent group of this group. Parent groups are used to establish a hierarchy of groups, providing an arbitrary hierarchy of groups.
EXPANDED indicates that, by default, the group should show up as “expanded”, so that the user immediately sees all of the components within the group. Otherwise, the group will initially show up as a single entry.
BOLD\_TITLE indicates that the group title should appear in bold, to call the user’s attention to the group.
`cpack_add_install_type`
Add a new installation type containing a set of predefined component selections to the graphical installer.
```
cpack_add_install_type(typename
[DISPLAY_NAME name])
```
The cpack\_add\_install\_type command identifies a set of preselected components that represents a common use case for an application. For example, a “Developer” install type might include an application along with its header and library files, while an “End user” install type might just include the application’s executable. Each component identifies itself with one or more install types via the INSTALL\_TYPES argument to cpack\_add\_component.
DISPLAY\_NAME is the displayed name of the install type, which will typically show up in a drop-down box within a graphical installer. This value can be any string.
`cpack_configure_downloads`
Configure CPack to download selected components on-the-fly as part of the installation process.
```
cpack_configure_downloads(site
[UPLOAD_DIRECTORY dirname]
[ALL]
[ADD_REMOVE|NO_ADD_REMOVE])
```
The cpack\_configure\_downloads command configures installation-time downloads of selected components. For each downloadable component, CPack will create an archive containing the contents of that component, which should be uploaded to the given site. When the user selects that component for installation, the installer will download and extract the component in place. This feature is useful for creating small installers that only download the requested components, saving bandwidth. Additionally, the installers are small enough that they will be installed as part of the normal installation process, and the “Change” button in Windows Add/Remove Programs control panel will allow one to add or remove parts of the application after the original installation. On Windows, the downloaded-components functionality requires the ZipDLL plug-in for NSIS, available at:
```
http://nsis.sourceforge.net/ZipDLL_plug-in
```
On Mac OS X, installers that download components on-the-fly can only be built and installed on system using Mac OS X 10.5 or later.
The site argument is a URL where the archives for downloadable components will reside, e.g., <https://cmake.org/files/2.6.1/installer/> All of the archives produced by CPack should be uploaded to that location.
UPLOAD\_DIRECTORY is the local directory where CPack will create the various archives for each of the components. The contents of this directory should be uploaded to a location accessible by the URL given in the site argument. If omitted, CPack will use the directory CPackUploads inside the CMake binary directory to store the generated archives.
The ALL flag indicates that all components be downloaded. Otherwise, only those components explicitly marked as DOWNLOADED or that have a specified ARCHIVE\_FILE will be downloaded. Additionally, the ALL option implies ADD\_REMOVE (unless NO\_ADD\_REMOVE is specified).
ADD\_REMOVE indicates that CPack should install a copy of the installer that can be called from Windows’ Add/Remove Programs dialog (via the “Modify” button) to change the set of installed components. NO\_ADD\_REMOVE turns off this behavior. This option is ignored on Mac OS X.
cmake WriteBasicConfigVersionFile WriteBasicConfigVersionFile
===========================
```
WRITE_BASIC_CONFIG_VERSION_FILE( filename
[VERSION major.minor.patch]
COMPATIBILITY (AnyNewerVersion|SameMajorVersion)
)
```
Deprecated, see WRITE\_BASIC\_PACKAGE\_VERSION\_FILE(), it is identical.
cmake FindOpenAL FindOpenAL
==========
Locate OpenAL This module defines OPENAL\_LIBRARY OPENAL\_FOUND, if false, do not try to link to OpenAL OPENAL\_INCLUDE\_DIR, where to find the headers
$OPENALDIR is an environment variable that would correspond to the ./configure –prefix=$OPENALDIR used in building OpenAL.
Created by Eric Wing. This was influenced by the FindSDL.cmake module.
cmake FindITK FindITK
=======
This module no longer exists.
This module existed in versions of CMake prior to 3.1, but became only a thin wrapper around `find_package(ITK NO_MODULE)` to provide compatibility for projects using long-outdated conventions. Now `find_package(ITK)` will search for `ITKConfig.cmake` directly.
cmake CPackDMG CPackDMG
========
DragNDrop CPack generator (Mac OS X).
Variables specific to CPack DragNDrop generator
-----------------------------------------------
The following variables are specific to the DragNDrop installers built on Mac OS X:
`CPACK_DMG_VOLUME_NAME`
The volume name of the generated disk image. Defaults to CPACK\_PACKAGE\_FILE\_NAME.
`CPACK_DMG_FORMAT`
The disk image format. Common values are UDRO (UDIF read-only), UDZO (UDIF zlib-compressed) or UDBZ (UDIF bzip2-compressed). Refer to hdiutil(1) for more information on other available formats. Defaults to UDZO.
`CPACK_DMG_DS_STORE`
Path to a custom DS\_Store file. This .DS\_Store file e.g. can be used to specify the Finder window position/geometry and layout (such as hidden toolbars, placement of the icons etc.). This file has to be generated by the Finder (either manually or through AppleScript) using a normal folder from which the .DS\_Store file can then be extracted.
`CPACK_DMG_DS_STORE_SETUP_SCRIPT`
Path to a custom AppleScript file. This AppleScript is used to generate a .DS\_Store file which specifies the Finder window position/geometry and layout (such as hidden toolbars, placement of the icons etc.). By specifying a custom AppleScript there is no need to use CPACK\_DMG\_DS\_STORE, as the .DS\_Store that is generated by the AppleScript will be packaged.
`CPACK_DMG_BACKGROUND_IMAGE`
Path to an image file to be used as the background. This file will be copied to .background/background.<ext>, where ext is the original image file extension. The background image is installed into the image before CPACK\_DMG\_DS\_STORE\_SETUP\_SCRIPT is executed or CPACK\_DMG\_DS\_STORE is installed. By default no background image is set.
`CPACK_DMG_DISABLE_APPLICATIONS_SYMLINK`
Default behaviour is to include a symlink to `/Applications` in the DMG. Set this option to `ON` to avoid adding the symlink.
`CPACK_DMG_SLA_DIR`
Directory where license and menu files for different languages are stored. Setting this causes CPack to look for a `<language>.menu.txt` and `<language>.license.txt` file for every language defined in `CPACK_DMG_SLA_LANGUAGES`. If both this variable and `CPACK_RESOURCE_FILE_LICENSE` are set, CPack will only look for the menu files and use the same license file for all languages.
`CPACK_DMG_SLA_LANGUAGES`
Languages for which a license agreement is provided when mounting the generated DMG. A menu file consists of 9 lines of text. The first line is is the name of the language itself, uppercase, in English (e.g. German). The other lines are translations of the following strings:
* Agree
* Disagree
* Print
* Save…
* You agree to the terms of the License Agreement when you click the “Agree” button.
* Software License Agreement
* This text cannot be saved. The disk may be full or locked, or the file may be locked.
* Unable to print. Make sure you have selected a printer.
For every language in this list, CPack will try to find files `<language>.menu.txt` and `<language>.license.txt` in the directory specified by the [`CPACK_DMG_SLA_DIR`](#variable:CPACK_DMG_SLA_DIR "CPACK_DMG_SLA_DIR") variable.
`CPACK_COMMAND_HDIUTIL`
Path to the hdiutil(1) command used to operate on disk image files on Mac OS X. This variable can be used to override the automatically detected command (or specify its location if the auto-detection fails to find it.)
`CPACK_COMMAND_SETFILE`
Path to the SetFile(1) command used to set extended attributes on files and directories on Mac OS X. This variable can be used to override the automatically detected command (or specify its location if the auto-detection fails to find it.)
`CPACK_COMMAND_REZ`
Path to the Rez(1) command used to compile resources on Mac OS X. This variable can be used to override the automatically detected command (or specify its location if the auto-detection fails to find it.)
cmake FindPythonLibs FindPythonLibs
==============
Find python libraries
This module finds if Python is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:
```
PYTHONLIBS_FOUND - have the Python libs been found
PYTHON_LIBRARIES - path to the python library
PYTHON_INCLUDE_PATH - path to where Python.h is found (deprecated)
PYTHON_INCLUDE_DIRS - path to where Python.h is found
PYTHON_DEBUG_LIBRARIES - path to the debug library (deprecated)
PYTHONLIBS_VERSION_STRING - version of the Python libs found (since CMake 2.8.8)
```
The Python\_ADDITIONAL\_VERSIONS variable can be used to specify a list of version numbers that should be taken into account when searching for Python. You need to set this variable before calling find\_package(PythonLibs).
If you’d like to specify the installation of Python to use, you should modify the following cache variables:
```
PYTHON_LIBRARY - path to the python library
PYTHON_INCLUDE_DIR - path to where Python.h is found
```
If calling both `find_package(PythonInterp)` and `find_package(PythonLibs)`, call `find_package(PythonInterp)` first to get the currently active Python version by default with a consistent version of PYTHON\_LIBRARIES.
| programming_docs |
cmake FindSDL_image FindSDL\_image
==============
Locate SDL\_image library
This module defines:
```
SDL_IMAGE_LIBRARIES, the name of the library to link against
SDL_IMAGE_INCLUDE_DIRS, where to find the headers
SDL_IMAGE_FOUND, if false, do not try to link against
SDL_IMAGE_VERSION_STRING - human-readable string containing the
version of SDL_image
```
For backward compatibility the following variables are also set:
```
SDLIMAGE_LIBRARY (same value as SDL_IMAGE_LIBRARIES)
SDLIMAGE_INCLUDE_DIR (same value as SDL_IMAGE_INCLUDE_DIRS)
SDLIMAGE_FOUND (same value as SDL_IMAGE_FOUND)
```
$SDLDIR is an environment variable that would correspond to the ./configure –prefix=$SDLDIR used in building SDL.
Created by Eric Wing. This was influenced by the FindSDL.cmake module, but with modifications to recognize OS X frameworks and additional Unix paths (FreeBSD, etc).
cmake ExternalData ExternalData
============
* [Introduction](#introduction)
* [Module Functions](#module-functions)
* [Module Variables](#module-variables)
* [Referencing Files](#referencing-files)
+ [Referencing Single Files](#referencing-single-files)
+ [Referencing File Series](#referencing-file-series)
+ [Referencing Associated Files](#referencing-associated-files)
+ [Referencing Directories](#referencing-directories)
* [Hash Algorithms](#hash-algorithms)
* [Custom Fetch Scripts](#custom-fetch-scripts)
Manage data files stored outside source tree
Introduction
------------
Use this module to unambiguously reference data files stored outside the source tree and fetch them at build time from arbitrary local and remote content-addressed locations. Functions provided by this module recognize arguments with the syntax `DATA{<name>}` as references to external data, replace them with full paths to local copies of those data, and create build rules to fetch and update the local copies.
For example:
```
include(ExternalData)
set(ExternalData_URL_TEMPLATES "file:///local/%(algo)/%(hash)"
"file:////host/share/%(algo)/%(hash)"
"http://data.org/%(algo)/%(hash)")
ExternalData_Add_Test(MyData
NAME MyTest
COMMAND MyExe DATA{MyInput.png}
)
ExternalData_Add_Target(MyData)
```
When test `MyTest` runs the `DATA{MyInput.png}` argument will be replaced by the full path to a real instance of the data file `MyInput.png` on disk. If the source tree contains a content link such as `MyInput.png.md5` then the `MyData` target creates a real `MyInput.png` in the build tree.
Module Functions
----------------
`ExternalData_Expand_Arguments`
The `ExternalData_Expand_Arguments` function evaluates `DATA{}` references in its arguments and constructs a new list of arguments:
```
ExternalData_Expand_Arguments(
<target> # Name of data management target
<outVar> # Output variable
[args...] # Input arguments, DATA{} allowed
)
```
It replaces each `DATA{}` reference in an argument with the full path of a real data file on disk that will exist after the `<target>` builds.
`ExternalData_Add_Test`
The `ExternalData_Add_Test` function wraps around the CMake [`add_test()`](../command/add_test#command:add_test "add_test") command but supports `DATA{}` references in its arguments:
```
ExternalData_Add_Test(
<target> # Name of data management target
... # Arguments of add_test(), DATA{} allowed
)
```
It passes its arguments through `ExternalData_Expand_Arguments` and then invokes the [`add_test()`](../command/add_test#command:add_test "add_test") command using the results.
`ExternalData_Add_Target`
The `ExternalData_Add_Target` function creates a custom target to manage local instances of data files stored externally:
```
ExternalData_Add_Target(
<target> # Name of data management target
)
```
It creates custom commands in the target as necessary to make data files available for each `DATA{}` reference previously evaluated by other functions provided by this module. Data files may be fetched from one of the URL templates specified in the `ExternalData_URL_TEMPLATES` variable, or may be found locally in one of the paths specified in the `ExternalData_OBJECT_STORES` variable.
Typically only one target is needed to manage all external data within a project. Call this function once at the end of configuration after all data references have been processed.
Module Variables
----------------
The following variables configure behavior. They should be set before calling any of the functions provided by this module.
`ExternalData_BINARY_ROOT`
The `ExternalData_BINARY_ROOT` variable may be set to the directory to hold the real data files named by expanded `DATA{}` references. The default is `CMAKE_BINARY_DIR`. The directory layout will mirror that of content links under `ExternalData_SOURCE_ROOT`.
`ExternalData_CUSTOM_SCRIPT_<key>`
Specify a full path to a `.cmake` custom fetch script identified by `<key>` in entries of the `ExternalData_URL_TEMPLATES` list. See [Custom Fetch Scripts](#custom-fetch-scripts).
`ExternalData_LINK_CONTENT`
The `ExternalData_LINK_CONTENT` variable may be set to the name of a supported hash algorithm to enable automatic conversion of real data files referenced by the `DATA{}` syntax into content links. For each such `<file>` a content link named `<file><ext>` is created. The original file is renamed to the form `.ExternalData_<algo>_<hash>` to stage it for future transmission to one of the locations in the list of URL templates (by means outside the scope of this module). The data fetch rule created for the content link will use the staged object if it cannot be found using any URL template.
`ExternalData_NO_SYMLINKS`
The real data files named by expanded `DATA{}` references may be made available under `ExternalData_BINARY_ROOT` using symbolic links on some platforms. The `ExternalData_NO_SYMLINKS` variable may be set to disable use of symbolic links and enable use of copies instead.
`ExternalData_OBJECT_STORES`
The `ExternalData_OBJECT_STORES` variable may be set to a list of local directories that store objects using the layout `<dir>/%(algo)/%(hash)`. These directories will be searched first for a needed object. If the object is not available in any store then it will be fetched remotely using the URL templates and added to the first local store listed. If no stores are specified the default is a location inside the build tree.
`ExternalData_SERIES_PARSE`
`ExternalData_SERIES_PARSE_PREFIX`
`ExternalData_SERIES_PARSE_NUMBER`
`ExternalData_SERIES_PARSE_SUFFIX`
`ExternalData_SERIES_MATCH`
See [Referencing File Series](#referencing-file-series).
`ExternalData_SOURCE_ROOT`
The `ExternalData_SOURCE_ROOT` variable may be set to the highest source directory containing any path named by a `DATA{}` reference. The default is `CMAKE_SOURCE_DIR`. `ExternalData_SOURCE_ROOT` and `CMAKE_SOURCE_DIR` must refer to directories within a single source distribution (e.g. they come together in one tarball).
`ExternalData_TIMEOUT_ABSOLUTE`
The `ExternalData_TIMEOUT_ABSOLUTE` variable sets the download absolute timeout, in seconds, with a default of `300` seconds. Set to `0` to disable enforcement.
`ExternalData_TIMEOUT_INACTIVITY`
The `ExternalData_TIMEOUT_INACTIVITY` variable sets the download inactivity timeout, in seconds, with a default of `60` seconds. Set to `0` to disable enforcement.
`ExternalData_URL_ALGO_<algo>_<key>`
Specify a custom URL component to be substituted for URL template placeholders of the form `%(algo:<key>)`, where `<key>` is a valid C identifier, when fetching an object referenced via hash algorithm `<algo>`. If not defined, the default URL component is just `<algo>` for any `<key>`.
`ExternalData_URL_TEMPLATES`
The `ExternalData_URL_TEMPLATES` may be set to provide a list of of URL templates using the placeholders `%(algo)` and `%(hash)` in each template. Data fetch rules try each URL template in order by substituting the hash algorithm name for `%(algo)` and the hash value for `%(hash)`. Alternatively one may use `%(algo:<key>)` with `ExternalData_URL_ALGO_<algo>_<key>` variables to gain more flexibility in remote URLs.
Referencing Files
-----------------
### Referencing Single Files
The `DATA{}` syntax is literal and the `<name>` is a full or relative path within the source tree. The source tree must contain either a real data file at `<name>` or a “content link” at `<name><ext>` containing a hash of the real file using a hash algorithm corresponding to `<ext>`. For example, the argument `DATA{img.png}` may be satisfied by either a real `img.png` file in the current source directory or a `img.png.md5` file containing its MD5 sum.
Multiple content links of the same name with different hash algorithms are supported (e.g. `img.png.sha256` and `img.png.sha1`) so long as they all correspond to the same real file. This allows objects to be fetched from sources indexed by different hash algorithms.
### Referencing File Series
The `DATA{}` syntax can be told to fetch a file series using the form `DATA{<name>,:}`, where the `:` is literal. If the source tree contains a group of files or content links named like a series then a reference to one member adds rules to fetch all of them. Although all members of a series are fetched, only the file originally named by the `DATA{}` argument is substituted for it. The default configuration recognizes file series names ending with `#.ext`, `_#.ext`, `.#.ext`, or `-#.ext` where `#` is a sequence of decimal digits and `.ext` is any single extension. Configure it with a regex that parses `<number>` and `<suffix>` parts from the end of `<name>`:
```
ExternalData_SERIES_PARSE = regex of the form (<number>)(<suffix>)$
```
For more complicated cases set:
```
ExternalData_SERIES_PARSE = regex with at least two () groups
ExternalData_SERIES_PARSE_PREFIX = <prefix> regex group number, if any
ExternalData_SERIES_PARSE_NUMBER = <number> regex group number
ExternalData_SERIES_PARSE_SUFFIX = <suffix> regex group number
```
Configure series number matching with a regex that matches the `<number>` part of series members named `<prefix><number><suffix>`:
```
ExternalData_SERIES_MATCH = regex matching <number> in all series members
```
Note that the `<suffix>` of a series does not include a hash-algorithm extension.
### Referencing Associated Files
The `DATA{}` syntax can alternatively match files associated with the named file and contained in the same directory. Associated files may be specified by options using the syntax `DATA{<name>,<opt1>,<opt2>,...}`. Each option may specify one file by name or specify a regular expression to match file names using the syntax `REGEX:<regex>`. For example, the arguments:
```
DATA{MyData/MyInput.mhd,MyInput.img} # File pair
DATA{MyData/MyFrames00.png,REGEX:MyFrames[0-9]+\\.png} # Series
```
will pass `MyInput.mha` and `MyFrames00.png` on the command line but ensure that the associated files are present next to them.
### Referencing Directories
The `DATA{}` syntax may reference a directory using a trailing slash and a list of associated files. The form `DATA{<name>/,<opt1>,<opt2>,...}` adds rules to fetch any files in the directory that match one of the associated file options. For example, the argument `DATA{MyDataDir/,REGEX:.*}` will pass the full path to a `MyDataDir` directory on the command line and ensure that the directory contains files corresponding to every file or content link in the `MyDataDir` source directory. In order to match associated files in subdirectories, specify a `RECURSE:` option, e.g. `DATA{MyDataDir/,RECURSE:,REGEX:.*}`.
Hash Algorithms
---------------
The following hash algorithms are supported:
```
%(algo) <ext> Description
------- ----- -----------
MD5 .md5 Message-Digest Algorithm 5, RFC 1321
SHA1 .sha1 US Secure Hash Algorithm 1, RFC 3174
SHA224 .sha224 US Secure Hash Algorithms, RFC 4634
SHA256 .sha256 US Secure Hash Algorithms, RFC 4634
SHA384 .sha384 US Secure Hash Algorithms, RFC 4634
SHA512 .sha512 US Secure Hash Algorithms, RFC 4634
SHA3_224 .sha3-224 Keccak SHA-3
SHA3_256 .sha3-256 Keccak SHA-3
SHA3_384 .sha3-384 Keccak SHA-3
SHA3_512 .sha3-512 Keccak SHA-3
```
Note that the hashes are used only for unique data identification and download verification.
Custom Fetch Scripts
--------------------
When a data file must be fetched from one of the URL templates specified in the `ExternalData_URL_TEMPLATES` variable, it is normally downloaded using the [`file(DOWNLOAD)`](../command/file#command:file "file") command. One may specify usage of a custom fetch script by using a URL template of the form `ExternalDataCustomScript://<key>/<loc>`. The `<key>` must be a C identifier, and the `<loc>` must contain the `%(algo)` and `%(hash)` placeholders. A variable corresponding to the key, `ExternalData_CUSTOM_SCRIPT_<key>`, must be set to the full path to a `.cmake` script file. The script will be included to perform the actual fetch, and provided with the following variables:
`ExternalData_CUSTOM_LOCATION`
When a custom fetch script is loaded, this variable is set to the location part of the URL, which will contain the substituted hash algorithm name and content hash value.
`ExternalData_CUSTOM_FILE`
When a custom fetch script is loaded, this variable is set to the full path to a file in which the script must store the fetched content. The name of the file is unspecified and should not be interpreted in any way.
The custom fetch script is expected to store fetched content in the file or set a variable:
`ExternalData_CUSTOM_ERROR`
When a custom fetch script fails to fetch the requested content, it must set this variable to a short one-line message describing the reason for failure.
cmake FindASPELL FindASPELL
==========
Try to find ASPELL
Once done this will define
```
ASPELL_FOUND - system has ASPELL
ASPELL_EXECUTABLE - the ASPELL executable
ASPELL_INCLUDE_DIR - the ASPELL include directory
ASPELL_LIBRARIES - The libraries needed to use ASPELL
ASPELL_DEFINITIONS - Compiler switches required for using ASPELL
```
cmake FindFLTK FindFLTK
========
Find the native FLTK includes and library
By default FindFLTK.cmake will search for all of the FLTK components and add them to the FLTK\_LIBRARIES variable.
```
You can limit the components which get placed in FLTK_LIBRARIES by
defining one or more of the following three options:
```
```
FLTK_SKIP_OPENGL, set to true to disable searching for opengl and
the FLTK GL library
FLTK_SKIP_FORMS, set to true to disable searching for fltk_forms
FLTK_SKIP_IMAGES, set to true to disable searching for fltk_images
```
```
FLTK_SKIP_FLUID, set to true if the fluid binary need not be present
at build time
```
The following variables will be defined:
```
FLTK_FOUND, True if all components not skipped were found
FLTK_INCLUDE_DIR, where to find include files
FLTK_LIBRARIES, list of fltk libraries you should link against
FLTK_FLUID_EXECUTABLE, where to find the Fluid tool
FLTK_WRAP_UI, This enables the FLTK_WRAP_UI command
```
The following cache variables are assigned but should not be used. See the FLTK\_LIBRARIES variable instead.
```
FLTK_BASE_LIBRARY = the full path to fltk.lib
FLTK_GL_LIBRARY = the full path to fltk_gl.lib
FLTK_FORMS_LIBRARY = the full path to fltk_forms.lib
FLTK_IMAGES_LIBRARY = the full path to fltk_images.lib
```
cmake CheckCXXSourceCompiles CheckCXXSourceCompiles
======================
Check if given C++ source compiles and links into an executable
CHECK\_CXX\_SOURCE\_COMPILES(<code> <var> [FAIL\_REGEX <fail-regex>])
```
<code> - source code to try to compile, must define 'main'
<var> - variable to store whether the source code compiled
Will be created as an internal cache variable.
<fail-regex> - fail if test output matches this regex
```
The following variables may be set before calling this macro to modify the way the check is run:
```
CMAKE_REQUIRED_FLAGS = string of compile command line flags
CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
CMAKE_REQUIRED_INCLUDES = list of include directories
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
CMAKE_REQUIRED_QUIET = execute quietly without messages
```
cmake CPackProductBuild CPackProductBuild
=================
productbuild CPack generator (Mac OS X).
Variables specific to CPack productbuild generator
--------------------------------------------------
The following variable is specific to installers built on Mac OS X using productbuild:
`CPACK_COMMAND_PRODUCTBUILD`
Path to the productbuild(1) command used to generate a product archive for the OS X Installer or Mac App Store. This variable can be used to override the automatically detected command (or specify its location if the auto-detection fails to find it.)
`CPACK_PRODUCTBUILD_IDENTITY_NAME`
Adds a digital signature to the resulting package.
`CPACK_PRODUCTBUILD_KEYCHAIN_PATH`
Specify a specific keychain to search for the signing identity.
`CPACK_COMMAND_PKGBUILD`
Path to the pkgbuild(1) command used to generate an OS X component package on OS X. This variable can be used to override the automatically detected command (or specify its location if the auto-detection fails to find it.)
`CPACK_PKGBUILD_IDENTITY_NAME`
Adds a digital signature to the resulting package.
`CPACK_PKGBUILD_KEYCHAIN_PATH`
Specify a specific keychain to search for the signing identity.
`CPACK_PRODUCTBUILD_RESOURCES_DIR`
If specified the productbuild generator copies files from this directory (including subdirectories) to the `Resources` directory. This is done before the [`CPACK_RESOURCE_FILE_WELCOME`](cpack#variable:CPACK_RESOURCE_FILE_WELCOME "CPACK_RESOURCE_FILE_WELCOME"), [`CPACK_RESOURCE_FILE_README`](cpack#variable:CPACK_RESOURCE_FILE_README "CPACK_RESOURCE_FILE_README"), and [`CPACK_RESOURCE_FILE_LICENSE`](cpack#variable:CPACK_RESOURCE_FILE_LICENSE "CPACK_RESOURCE_FILE_LICENSE") files are copied.
cmake FindGnuplot FindGnuplot
===========
this module looks for gnuplot
Once done this will define
```
GNUPLOT_FOUND - system has Gnuplot
GNUPLOT_EXECUTABLE - the Gnuplot executable
GNUPLOT_VERSION_STRING - the version of Gnuplot found (since CMake 2.8.8)
```
GNUPLOT\_VERSION\_STRING will not work for old versions like 3.7.1.
cmake FindosgIntrospection FindosgIntrospection
====================
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgINTROSPECTION This module defines
OSGINTROSPECTION\_FOUND - Was osgIntrospection found? OSGINTROSPECTION\_INCLUDE\_DIR - Where to find the headers OSGINTROSPECTION\_LIBRARIES - The libraries to link for osgIntrospection (use this)
OSGINTROSPECTION\_LIBRARY - The osgIntrospection library OSGINTROSPECTION\_LIBRARY\_DEBUG - The osgIntrospection debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake FindLibLZMA FindLibLZMA
===========
Find LibLZMA
Find LibLZMA headers and library
```
LIBLZMA_FOUND - True if liblzma is found.
LIBLZMA_INCLUDE_DIRS - Directory where liblzma headers are located.
LIBLZMA_LIBRARIES - Lzma libraries to link against.
LIBLZMA_HAS_AUTO_DECODER - True if lzma_auto_decoder() is found (required).
LIBLZMA_HAS_EASY_ENCODER - True if lzma_easy_encoder() is found (required).
LIBLZMA_HAS_LZMA_PRESET - True if lzma_lzma_preset() is found (required).
LIBLZMA_VERSION_MAJOR - The major version of lzma
LIBLZMA_VERSION_MINOR - The minor version of lzma
LIBLZMA_VERSION_PATCH - The patch version of lzma
LIBLZMA_VERSION_STRING - version number as a string (ex: "5.0.3")
```
| programming_docs |
cmake CMakeFindFrameworks CMakeFindFrameworks
===================
helper module to find OSX frameworks
This module reads hints about search locations from variables:
```
CMAKE_FIND_FRAMEWORK_EXTRA_LOCATIONS - Extra directories
```
cmake FindBLAS FindBLAS
========
Find BLAS library
This module finds an installed fortran library that implements the BLAS linear-algebra interface (see <http://www.netlib.org/blas/>). The list of libraries searched for is taken from the autoconf macro file, acx\_blas.m4 (distributed at <http://ac-archive.sourceforge.net/ac-archive/acx_blas.html>).
This module sets the following variables:
```
BLAS_FOUND - set to true if a library implementing the BLAS interface
is found
BLAS_LINKER_FLAGS - uncached list of required linker flags (excluding -l
and -L).
BLAS_LIBRARIES - uncached list of libraries (using full path name) to
link against to use BLAS
BLAS95_LIBRARIES - uncached list of libraries (using full path name)
to link against to use BLAS95 interface
BLAS95_FOUND - set to true if a library implementing the BLAS f95 interface
is found
BLA_STATIC if set on this determines what kind of linkage we do (static)
BLA_VENDOR if set checks only the specified vendor, if not set checks
all the possibilities
BLA_F95 if set on tries to find the f95 interfaces for BLAS/LAPACK
```
List of vendors (BLA\_VENDOR) valid in this module:
* Goto
* OpenBLAS
* ATLAS PhiPACK
* CXML
* DXML
* SunPerf
* SCSL
* SGIMATH
* IBMESSL
* Intel10\_32 (intel mkl v10 32 bit)
* Intel10\_64lp (intel mkl v10 64 bit, lp thread model, lp64 model)
* Intel10\_64lp\_seq (intel mkl v10 64 bit, sequential code, lp64 model)
* Intel (older versions of mkl 32 and 64 bit)
* ACML
* ACML\_MP
* ACML\_GPU
* Apple
* NAS
* Generic
Note
C/CXX should be enabled to use Intel mkl
cmake Documentation Documentation
=============
DocumentationVTK.cmake
This file provides support for the VTK documentation framework. It relies on several tools (Doxygen, Perl, etc).
cmake FindOpenSSL FindOpenSSL
===========
Find the OpenSSL encryption library.
Imported Targets
----------------
This module defines the following [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets:
`OpenSSL::SSL` The OpenSSL `ssl` library, if found.
`OpenSSL::Crypto` The OpenSSL `crypto` library, if found. Result Variables
----------------
This module will set the following variables in your project:
`OPENSSL_FOUND` System has the OpenSSL library.
`OPENSSL_INCLUDE_DIR` The OpenSSL include directory.
`OPENSSL_CRYPTO_LIBRARY` The OpenSSL crypto library.
`OPENSSL_SSL_LIBRARY` The OpenSSL SSL library.
`OPENSSL_LIBRARIES` All OpenSSL libraries.
`OPENSSL_VERSION` This is set to `$major.$minor.$revision$patch` (e.g. `0.9.8s`). Hints
-----
Set `OPENSSL_ROOT_DIR` to the root directory of an OpenSSL installation. Set `OPENSSL_USE_STATIC_LIBS` to `TRUE` to look for static libraries. Set `OPENSSL_MSVC_STATIC_RT` set `TRUE` to choose the MT version of the lib.
cmake FindLATEX FindLATEX
=========
Find Latex
This module finds an installed Latex and determines the location of the compiler. Additionally the module looks for Latex-related software like BibTeX.
This module sets the following result variables:
```
LATEX_FOUND: whether found Latex and requested components
LATEX_<component>_FOUND: whether found <component>
LATEX_COMPILER: path to the LaTeX compiler
PDFLATEX_COMPILER: path to the PdfLaTeX compiler
XELATEX_COMPILER: path to the XeLaTeX compiler
LUALATEX_COMPILER: path to the LuaLaTeX compiler
BIBTEX_COMPILER: path to the BibTeX compiler
BIBER_COMPILER: path to the Biber compiler
MAKEINDEX_COMPILER: path to the MakeIndex compiler
XINDY_COMPILER: path to the xindy compiler
DVIPS_CONVERTER: path to the DVIPS converter
DVIPDF_CONVERTER: path to the DVIPDF converter
PS2PDF_CONVERTER: path to the PS2PDF converter
PDFTOPS_CONVERTER: path to the pdftops converter
LATEX2HTML_CONVERTER: path to the LaTeX2Html converter
HTLATEX_COMPILER: path to the htlatex compiler
```
Possible components are:
```
PDFLATEX
XELATEX
LUALATEX
BIBTEX
BIBER
MAKEINDEX
XINDY
DVIPS
DVIPDF
PS2PDF
PDFTOPS
LATEX2HTML
HTLATEX
```
Example Usages:
```
find_package(LATEX)
find_package(LATEX COMPONENTS PDFLATEX)
find_package(LATEX COMPONENTS BIBTEX PS2PDF)
```
cmake FindXercesC FindXercesC
===========
Find the Apache Xerces-C++ validating XML parser headers and libraries.
Imported targets
----------------
This module defines the following [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets:
`XercesC::XercesC` The Xerces-C++ `xerces-c` library, if found. Result variables
----------------
This module will set the following variables in your project:
`XercesC_FOUND` true if the Xerces headers and libraries were found
`XercesC_VERSION` Xerces release version
`XercesC_INCLUDE_DIRS` the directory containing the Xerces headers
`XercesC_LIBRARIES` Xerces libraries to be linked Cache variables
---------------
The following cache variables may also be set:
`XercesC_INCLUDE_DIR` the directory containing the Xerces headers
`XercesC_LIBRARY` the Xerces library
cmake FindMotif FindMotif
=========
Try to find Motif (or lesstif)
Once done this will define:
```
MOTIF_FOUND - system has MOTIF
MOTIF_INCLUDE_DIR - include paths to use Motif
MOTIF_LIBRARIES - Link these to use Motif
```
cmake FindQt FindQt
======
Searches for all installed versions of Qt.
This should only be used if your project can work with multiple versions of Qt. If not, you should just directly use FindQt4 or FindQt3. If multiple versions of Qt are found on the machine, then The user must set the option DESIRED\_QT\_VERSION to the version they want to use. If only one version of qt is found on the machine, then the DESIRED\_QT\_VERSION is set to that version and the matching FindQt3 or FindQt4 module is included. Once the user sets DESIRED\_QT\_VERSION, then the FindQt3 or FindQt4 module is included.
This module can only detect and switch between Qt versions 3 and 4. It cannot handle Qt5 or any later versions.
```
QT_REQUIRED if this is set to TRUE then if CMake can
not find Qt4 or Qt3 an error is raised
and a message is sent to the user.
```
```
DESIRED_QT_VERSION OPTION is created
QT4_INSTALLED is set to TRUE if qt4 is found.
QT3_INSTALLED is set to TRUE if qt3 is found.
```
cmake FindProducer FindProducer
============
Though Producer isn’t directly part of OpenSceneGraph, its primary user is OSG so I consider this part of the Findosg\* suite used to find OpenSceneGraph components. You’ll notice that I accept OSGDIR as an environment path.
Each component is separate and you must opt in to each module. You must also opt into OpenGL (and OpenThreads?) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate Producer This module defines PRODUCER\_LIBRARY PRODUCER\_FOUND, if false, do not try to link to Producer PRODUCER\_INCLUDE\_DIR, where to find the headers
$PRODUCER\_DIR is an environment variable that would correspond to the ./configure –prefix=$PRODUCER\_DIR used in building osg.
Created by Eric Wing.
cmake FindBISON FindBISON
=========
Find `bison` executable and provide a macro to generate custom build rules.
The module defines the following variables:
`BISON_EXECUTABLE` path to the `bison` program
`BISON_VERSION` version of `bison`
`BISON_FOUND` true if the program was found The minimum required version of `bison` can be specified using the standard CMake syntax, e.g. `find_package(BISON 2.1.3)`.
If `bison` is found, the module defines the macro:
```
BISON_TARGET(<Name> <YaccInput> <CodeOutput>
[COMPILE_FLAGS <flags>]
[DEFINES_FILE <file>]
[VERBOSE [<file>]]
[REPORT_FILE <file>]
)
```
which will create a custom rule to generate a parser. `<YaccInput>` is the path to a yacc file. `<CodeOutput>` is the name of the source file generated by bison. A header file is also be generated, and contains the token list.
The options are:
`COMPILE_FLAGS <flags>` Specify flags to be added to the `bison` command line.
`DEFINES_FILE <file>` Specify a non-default header `<file>` to be generated by `bison`.
`VERBOSE [<file>]` Tell `bison` to write a report file of the grammar and parser. If `<file>` is given, it specifies path the report file is copied to. `[<file>]` is left for backward compatibility of this module. Use `VERBOSE REPORT_FILE <file>`.
`REPORT_FILE <file>` Specify a non-default report `<file>`, if generated. The macro defines the following variables:
`BISON_<Name>_DEFINED` true is the macro ran successfully
`BISON_<Name>_INPUT` The input source file, an alias for <YaccInput>
`BISON_<Name>_OUTPUT_SOURCE` The source file generated by bison
`BISON_<Name>_OUTPUT_HEADER` The header file generated by bison
`BISON_<Name>_OUTPUTS` All files generated by bison including the source, the header and the report
`BISON_<Name>_COMPILE_FLAGS` Options used in the `bison` command line Example usage:
```
find_package(BISON)
BISON_TARGET(MyParser parser.y ${CMAKE_CURRENT_BINARY_DIR}/parser.cpp
DEFINES_FILE ${CMAKE_CURRENT_BINARY_DIR}/parser.h)
add_executable(Foo main.cpp ${BISON_MyParser_OUTPUTS})
```
cmake CheckFunctionExists CheckFunctionExists
===================
Check if a C function can be linked:
```
check_function_exists(<function> <variable>)
```
Check that the `<function>` is provided by libraries on the system and store the result in a `<variable>`. `<variable>` will be created as an internal cache variable.
The following variables may be set before calling this macro to modify the way the check is run:
```
CMAKE_REQUIRED_FLAGS = string of compile command line flags
CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
CMAKE_REQUIRED_INCLUDES = list of include directories
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
CMAKE_REQUIRED_QUIET = execute quietly without messages
```
Note
Prefer using [`CheckSymbolExists`](checksymbolexists#module:CheckSymbolExists "CheckSymbolExists") instead of this module, for the following reasons:
* `check_function_exists()` can’t detect functions that are inlined in headers or specified as a macro.
* `check_function_exists()` can’t detect anything in the 32-bit versions of the Win32 API, because of a mismatch in calling conventions.
* `check_function_exists()` only verifies linking, it does not verify that the function is declared in system headers.
cmake UseJavaClassFilelist UseJavaClassFilelist
====================
This script create a list of compiled Java class files to be added to a jar file. This avoids including cmake files which get created in the binary directory.
cmake FindEXPAT FindEXPAT
=========
Find expat
Find the native EXPAT headers and libraries.
```
EXPAT_INCLUDE_DIRS - where to find expat.h, etc.
EXPAT_LIBRARIES - List of libraries when using expat.
EXPAT_FOUND - True if expat found.
```
cmake FindosgViewer FindosgViewer
=============
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgViewer This module defines
OSGVIEWER\_FOUND - Was osgViewer found? OSGVIEWER\_INCLUDE\_DIR - Where to find the headers OSGVIEWER\_LIBRARIES - The libraries to link for osgViewer (use this)
OSGVIEWER\_LIBRARY - The osgViewer library OSGVIEWER\_LIBRARY\_DEBUG - The osgViewer debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake FindOpenCL FindOpenCL
==========
Try to find OpenCL
IMPORTED Targets
----------------
This module defines [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target `OpenCL::OpenCL`, if OpenCL has been found.
Result Variables
----------------
This module defines the following variables:
```
OpenCL_FOUND - True if OpenCL was found
OpenCL_INCLUDE_DIRS - include directories for OpenCL
OpenCL_LIBRARIES - link against this library to use OpenCL
OpenCL_VERSION_STRING - Highest supported OpenCL version (eg. 1.2)
OpenCL_VERSION_MAJOR - The major version of the OpenCL implementation
OpenCL_VERSION_MINOR - The minor version of the OpenCL implementation
```
The module will also define two cache variables:
```
OpenCL_INCLUDE_DIR - the OpenCL include directory
OpenCL_LIBRARY - the path to the OpenCL library
```
cmake CheckCXXSymbolExists CheckCXXSymbolExists
====================
Check if a symbol exists as a function, variable, or macro in C++
CHECK\_CXX\_SYMBOL\_EXISTS(<symbol> <files> <variable>)
Check that the <symbol> is available after including given header <files> and store the result in a <variable>. Specify the list of files in one argument as a semicolon-separated list. CHECK\_CXX\_SYMBOL\_EXISTS() can be used to check in C++ files, as opposed to CHECK\_SYMBOL\_EXISTS(), which works only for C.
If the header files define the symbol as a macro it is considered available and assumed to work. If the header files declare the symbol as a function or variable then the symbol must also be available for linking. If the symbol is a type or enum value it will not be recognized (consider using CheckTypeSize or CheckCSourceCompiles).
The following variables may be set before calling this macro to modify the way the check is run:
```
CMAKE_REQUIRED_FLAGS = string of compile command line flags
CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
CMAKE_REQUIRED_INCLUDES = list of include directories
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
CMAKE_REQUIRED_QUIET = execute quietly without messages
```
cmake CPackNSIS CPackNSIS
=========
CPack NSIS generator specific options
Variables specific to CPack NSIS generator
------------------------------------------
The following variables are specific to the graphical installers built on Windows using the Nullsoft Installation System.
`CPACK_NSIS_INSTALL_ROOT`
The default installation directory presented to the end user by the NSIS installer is under this root dir. The full directory presented to the end user is: ${CPACK\_NSIS\_INSTALL\_ROOT}/${CPACK\_PACKAGE\_INSTALL\_DIRECTORY}
`CPACK_NSIS_MUI_ICON`
An icon filename. The name of a `*.ico` file used as the main icon for the generated install program.
`CPACK_NSIS_MUI_UNIICON`
An icon filename. The name of a `*.ico` file used as the main icon for the generated uninstall program.
`CPACK_NSIS_INSTALLER_MUI_ICON_CODE`
undocumented.
`CPACK_NSIS_MUI_WELCOMEFINISHPAGE_BITMAP`
The filename of a bitmap to use as the NSIS MUI\_WELCOMEFINISHPAGE\_BITMAP.
`CPACK_NSIS_MUI_UNWELCOMEFINISHPAGE_BITMAP`
The filename of a bitmap to use as the NSIS MUI\_UNWELCOMEFINISHPAGE\_BITMAP.
`CPACK_NSIS_EXTRA_PREINSTALL_COMMANDS`
Extra NSIS commands that will be added to the beginning of the install Section, before your install tree is available on the target system.
`CPACK_NSIS_EXTRA_INSTALL_COMMANDS`
Extra NSIS commands that will be added to the end of the install Section, after your install tree is available on the target system.
`CPACK_NSIS_EXTRA_UNINSTALL_COMMANDS`
Extra NSIS commands that will be added to the uninstall Section, before your install tree is removed from the target system.
`CPACK_NSIS_COMPRESSOR`
The arguments that will be passed to the NSIS SetCompressor command.
`CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL`
Ask about uninstalling previous versions first. If this is set to “ON”, then an installer will look for previous installed versions and if one is found, ask the user whether to uninstall it before proceeding with the install.
`CPACK_NSIS_MODIFY_PATH`
Modify PATH toggle. If this is set to “ON”, then an extra page will appear in the installer that will allow the user to choose whether the program directory should be added to the system PATH variable.
`CPACK_NSIS_DISPLAY_NAME`
The display name string that appears in the Windows Add/Remove Program control panel
`CPACK_NSIS_PACKAGE_NAME`
The title displayed at the top of the installer.
`CPACK_NSIS_INSTALLED_ICON_NAME`
A path to the executable that contains the installer icon.
`CPACK_NSIS_HELP_LINK`
URL to a web site providing assistance in installing your application.
`CPACK_NSIS_URL_INFO_ABOUT`
URL to a web site providing more information about your application.
`CPACK_NSIS_CONTACT`
Contact information for questions and comments about the installation process.
`CPACK_NSIS_<compName>_INSTALL_DIRECTORY`
Custom install directory for the specified component <compName> instead of $INSTDIR.
`CPACK_NSIS_CREATE_ICONS_EXTRA`
Additional NSIS commands for creating start menu shortcuts.
`CPACK_NSIS_DELETE_ICONS_EXTRA`
Additional NSIS commands to uninstall start menu shortcuts.
`CPACK_NSIS_EXECUTABLES_DIRECTORY`
Creating NSIS start menu links assumes that they are in ‘bin’ unless this variable is set. For example, you would set this to ‘exec’ if your executables are in an exec directory.
`CPACK_NSIS_MUI_FINISHPAGE_RUN`
Specify an executable to add an option to run on the finish page of the NSIS installer.
`CPACK_NSIS_MENU_LINKS`
Specify links in [application] menu. This should contain a list of pair “link” “link name”. The link may be an URL or a path relative to installation prefix. Like:
```
set(CPACK_NSIS_MENU_LINKS
"doc/cmake-@CMake_VERSION_MAJOR@.@CMake_VERSION_MINOR@/cmake.html"
"CMake Help" "https://cmake.org" "CMake Web Site")
```
cmake CMakePrintHelpers CMakePrintHelpers
=================
Convenience macros for printing properties and variables, useful e.g. for debugging.
```
CMAKE_PRINT_PROPERTIES([TARGETS target1 .. targetN]
[SOURCES source1 .. sourceN]
[DIRECTORIES dir1 .. dirN]
[TESTS test1 .. testN]
[CACHE_ENTRIES entry1 .. entryN]
PROPERTIES prop1 .. propN )
```
This macro prints the values of the properties of the given targets, source files, directories, tests or cache entries. Exactly one of the scope keywords must be used. Example:
```
cmake_print_properties(TARGETS foo bar PROPERTIES
LOCATION INTERFACE_INCLUDE_DIRS)
```
This will print the LOCATION and INTERFACE\_INCLUDE\_DIRS properties for both targets foo and bar.
CMAKE\_PRINT\_VARIABLES(var1 var2 .. varN)
This macro will print the name of each variable followed by its value. Example:
```
cmake_print_variables(CMAKE_C_COMPILER CMAKE_MAJOR_VERSION DOES_NOT_EXIST)
```
Gives:
```
-- CMAKE_C_COMPILER="/usr/bin/gcc" ; CMAKE_MAJOR_VERSION="2" ; DOES_NOT_EXIST=""
```
cmake FindIce FindIce
=======
Find the ZeroC Internet Communication Engine (ICE) programs, libraries and datafiles.
This module supports multiple components. Components can include any of: `Freeze`, `Glacier2`, `Ice`, `IceBox`, `IceDB`, `IceGrid`, `IcePatch`, `IceSSL`, `IceStorm`, `IceUtil`, `IceXML`, or `Slice`.
This module reports information about the Ice installation in several variables. General variables:
```
Ice_VERSION - Ice release version
Ice_FOUND - true if the main programs and libraries were found
Ice_LIBRARIES - component libraries to be linked
Ice_INCLUDE_DIRS - the directories containing the Ice headers
Ice_SLICE_DIRS - the directories containing the Ice slice interface
definitions
```
Imported targets:
```
Ice::<C>
```
Where `<C>` is the name of an Ice component, for example `Ice::Glacier2`.
Ice slice programs are reported in:
```
Ice_SLICE2CPP_EXECUTABLE - path to slice2cpp executable
Ice_SLICE2CS_EXECUTABLE - path to slice2cs executable
Ice_SLICE2FREEZEJ_EXECUTABLE - path to slice2freezej executable
Ice_SLICE2FREEZE_EXECUTABLE - path to slice2freeze executable
Ice_SLICE2HTML_EXECUTABLE - path to slice2html executable
Ice_SLICE2JAVA_EXECUTABLE - path to slice2java executable
Ice_SLICE2JS_EXECUTABLE - path to slice2js executable
Ice_SLICE2PHP_EXECUTABLE - path to slice2php executable
Ice_SLICE2PY_EXECUTABLE - path to slice2py executable
Ice_SLICE2RB_EXECUTABLE - path to slice2rb executable
```
Ice programs are reported in:
```
Ice_GLACIER2ROUTER_EXECUTABLE - path to glacier2router executable
Ice_ICEBOX_EXECUTABLE - path to icebox executable
Ice_ICEBOXADMIN_EXECUTABLE - path to iceboxadmin executable
Ice_ICEBOXD_EXECUTABLE - path to iceboxd executable
Ice_ICEBOXNET_EXECUTABLE - path to iceboxnet executable
Ice_ICEGRIDADMIN_EXECUTABLE - path to icegridadmin executable
Ice_ICEGRIDNODE_EXECUTABLE - path to icegridnode executable
Ice_ICEGRIDNODED_EXECUTABLE - path to icegridnoded executable
Ice_ICEGRIDREGISTRY_EXECUTABLE - path to icegridregistry executable
Ice_ICEGRIDREGISTRYD_EXECUTABLE - path to icegridregistryd executable
Ice_ICEPATCH2CALC_EXECUTABLE - path to icepatch2calc executable
Ice_ICEPATCH2CLIENT_EXECUTABLE - path to icepatch2client executable
Ice_ICEPATCH2SERVER_EXECUTABLE - path to icepatch2server executable
Ice_ICESERVICEINSTALL_EXECUTABLE - path to iceserviceinstall executable
Ice_ICESTORMADMIN_EXECUTABLE - path to icestormadmin executable
Ice_ICESTORMMIGRATE_EXECUTABLE - path to icestormmigrate executable
```
Ice db programs (Windows only; standard system versions on all other platforms) are reported in:
```
Ice_DB_ARCHIVE_EXECUTABLE - path to db_archive executable
Ice_DB_CHECKPOINT_EXECUTABLE - path to db_checkpoint executable
Ice_DB_DEADLOCK_EXECUTABLE - path to db_deadlock executable
Ice_DB_DUMP_EXECUTABLE - path to db_dump executable
Ice_DB_HOTBACKUP_EXECUTABLE - path to db_hotbackup executable
Ice_DB_LOAD_EXECUTABLE - path to db_load executable
Ice_DB_LOG_VERIFY_EXECUTABLE - path to db_log_verify executable
Ice_DB_PRINTLOG_EXECUTABLE - path to db_printlog executable
Ice_DB_RECOVER_EXECUTABLE - path to db_recover executable
Ice_DB_STAT_EXECUTABLE - path to db_stat executable
Ice_DB_TUNER_EXECUTABLE - path to db_tuner executable
Ice_DB_UPGRADE_EXECUTABLE - path to db_upgrade executable
Ice_DB_VERIFY_EXECUTABLE - path to db_verify executable
Ice_DUMPDB_EXECUTABLE - path to dumpdb executable
Ice_TRANSFORMDB_EXECUTABLE - path to transformdb executable
```
Ice component libraries are reported in:
```
Ice_<C>_FOUND - ON if component was found
Ice_<C>_LIBRARIES - libraries for component
```
Note that `<C>` is the uppercased name of the component.
This module reads hints about search results from:
```
Ice_HOME - the root of the Ice installation
```
The environment variable `ICE_HOME` may also be used; the Ice\_HOME variable takes precedence.
The following cache variables may also be set:
```
Ice_<P>_EXECUTABLE - the path to executable <P>
Ice_INCLUDE_DIR - the directory containing the Ice headers
Ice_SLICE_DIR - the directory containing the Ice slice interface
definitions
Ice_<C>_LIBRARY - the library for component <C>
```
Note
In most cases none of the above variables will require setting, unless multiple Ice versions are available and a specific version is required. On Windows, the most recent version of Ice will be found through the registry. On Unix, the programs, headers and libraries will usually be in standard locations, but Ice\_SLICE\_DIRS might not be automatically detected (commonly known locations are searched). All the other variables are defaulted using Ice\_HOME, if set. It’s possible to set Ice\_HOME and selectively specify alternative locations for the other components; this might be required for e.g. newer versions of Visual Studio if the heuristics are not sufficient to identify the correct programs and libraries for the specific Visual Studio version.
Other variables one may set to control this module are:
```
Ice_DEBUG - Set to ON to enable debug output from FindIce.
```
| programming_docs |
cmake FindThreads FindThreads
===========
This module determines the thread library of the system.
The following variables are set
```
CMAKE_THREAD_LIBS_INIT - the thread library
CMAKE_USE_SPROC_INIT - are we using sproc?
CMAKE_USE_WIN32_THREADS_INIT - using WIN32 threads?
CMAKE_USE_PTHREADS_INIT - are we using pthreads
CMAKE_HP_PTHREADS_INIT - are we using hp pthreads
```
The following import target is created
```
Threads::Threads
```
For systems with multiple thread libraries, caller can set
```
CMAKE_THREAD_PREFER_PTHREAD
```
If the use of the -pthread compiler and linker flag is preferred then the caller can set
```
THREADS_PREFER_PTHREAD_FLAG
```
Please note that the compiler flag can only be used with the imported target. Use of both the imported target as well as this switch is highly recommended for new code.
cmake UseJava UseJava
=======
Use Module for Java
This file provides functions for Java. It is assumed that FindJava.cmake has already been loaded. See FindJava.cmake for information on how to load Java into your CMake project.
```
add_jar(target_name
[SOURCES] source1 [source2 ...] [resource1 ...]
[INCLUDE_JARS jar1 [jar2 ...]]
[ENTRY_POINT entry]
[VERSION version]
[OUTPUT_NAME name]
[OUTPUT_DIR dir]
)
```
This command creates a <target\_name>.jar. It compiles the given source files (source) and adds the given resource files (resource) to the jar file. Source files can be java files or listing files (prefixed by ‘@’). If only resource files are given then just a jar file is created. The list of include jars are added to the classpath when compiling the java sources and also to the dependencies of the target. INCLUDE\_JARS also accepts other target names created by add\_jar. For backwards compatibility, jar files listed as sources are ignored (as they have been since the first version of this module).
The default OUTPUT\_DIR can also be changed by setting the variable CMAKE\_JAVA\_TARGET\_OUTPUT\_DIR.
Additional instructions:
```
To add compile flags to the target you can set these flags with
the following variable:
```
```
set(CMAKE_JAVA_COMPILE_FLAGS -nowarn)
```
```
To add a path or a jar file to the class path you can do this
with the CMAKE_JAVA_INCLUDE_PATH variable.
```
```
set(CMAKE_JAVA_INCLUDE_PATH /usr/share/java/shibboleet.jar)
```
```
To use a different output name for the target you can set it with:
```
```
add_jar(foobar foobar.java OUTPUT_NAME shibboleet.jar)
```
```
To use a different output directory than CMAKE_CURRENT_BINARY_DIR
you can set it with:
```
```
add_jar(foobar foobar.java OUTPUT_DIR ${PROJECT_BINARY_DIR}/bin)
```
```
To define an entry point in your jar you can set it with the ENTRY_POINT
named argument:
```
```
add_jar(example ENTRY_POINT com/examples/MyProject/Main)
```
```
To define a custom manifest for the jar, you can set it with the manifest
named argument:
```
```
add_jar(example MANIFEST /path/to/manifest)
```
```
To add a VERSION to the target output name you can set it using
the VERSION named argument to add_jar. This will create a jar file with the
name shibboleet-1.0.0.jar and will create a symlink shibboleet.jar
pointing to the jar with the version information.
```
```
add_jar(shibboleet shibbotleet.java VERSION 1.2.0)
```
```
If the target is a JNI library, utilize the following commands to
create a JNI symbolic link:
```
```
set(CMAKE_JNI_TARGET TRUE)
add_jar(shibboleet shibbotleet.java VERSION 1.2.0)
install_jar(shibboleet ${LIB_INSTALL_DIR}/shibboleet)
install_jni_symlink(shibboleet ${JAVA_LIB_INSTALL_DIR})
```
```
If a single target needs to produce more than one jar from its
java source code, to prevent the accumulation of duplicate class
files in subsequent jars, set/reset CMAKE_JAR_CLASSES_PREFIX prior
to calling the add_jar() function:
```
```
set(CMAKE_JAR_CLASSES_PREFIX com/redhat/foo)
add_jar(foo foo.java)
```
```
set(CMAKE_JAR_CLASSES_PREFIX com/redhat/bar)
add_jar(bar bar.java)
```
Target Properties:
```
The add_jar() function sets some target properties. You can get these
properties with the
get_property(TARGET <target_name> PROPERTY <propery_name>)
command.
```
```
INSTALL_FILES The files which should be installed. This is used by
install_jar().
JNI_SYMLINK The JNI symlink which should be installed.
This is used by install_jni_symlink().
JAR_FILE The location of the jar file so that you can include
it.
CLASSDIR The directory where the class files can be found. For
example to use them with javah.
```
```
find_jar(<VAR>
name | NAMES name1 [name2 ...]
[PATHS path1 [path2 ... ENV var]]
[VERSIONS version1 [version2]]
[DOC "cache documentation string"]
)
```
This command is used to find a full path to the named jar. A cache entry named by <VAR> is created to stor the result of this command. If the full path to a jar is found the result is stored in the variable and the search will not repeated unless the variable is cleared. If nothing is found, the result will be <VAR>-NOTFOUND, and the search will be attempted again next time find\_jar is invoked with the same variable. The name of the full path to a file that is searched for is specified by the names listed after NAMES argument. Additional search locations can be specified after the PATHS argument. If you require special a version of a jar file you can specify it with the VERSIONS argument. The argument after DOC will be used for the documentation string in the cache.
```
install_jar(target_name destination)
install_jar(target_name DESTINATION destination [COMPONENT component])
```
This command installs the TARGET\_NAME files to the given DESTINATION. It should be called in the same scope as add\_jar() or it will fail.
Target Properties:
```
The install_jar() function sets the INSTALL_DESTINATION target property
on jars so installed. This property holds the DESTINATION as described
above, and is used by install_jar_exports(). You can get this property
with the
get_property(TARGET <target_name> PROPERTY INSTALL_DESTINATION)
command.
```
```
install_jni_symlink(target_name destination)
install_jni_symlink(target_name DESTINATION destination [COMPONENT component])
```
This command installs the TARGET\_NAME JNI symlinks to the given DESTINATION. It should be called in the same scope as add\_jar() or it will fail.
```
install_jar_exports(TARGETS jars...
[NAMESPACE <namespace>]
FILE <filename>
DESTINATION <dir> [COMPONENT <component>])
```
This command installs a target export file `<filename>` for the named jar targets to the given `DESTINATION`. Its function is similar to that of [`install(EXPORTS ...)`](../command/install#command:install "install").
```
export_jars(TARGETS jars...
[NAMESPACE <namespace>]
FILE <filename>)
```
This command writes a target export file `<filename>` for the named jar targets. Its function is similar to that of [`export(...)`](../command/export#command:export "export").
```
create_javadoc(<VAR>
PACKAGES pkg1 [pkg2 ...]
[SOURCEPATH <sourcepath>]
[CLASSPATH <classpath>]
[INSTALLPATH <install path>]
[DOCTITLE "the documentation title"]
[WINDOWTITLE "the title of the document"]
[AUTHOR TRUE|FALSE]
[USE TRUE|FALSE]
[VERSION TRUE|FALSE]
)
```
Create java documentation based on files or packages. For more details please read the javadoc manpage.
There are two main signatures for create\_javadoc. The first signature works with package names on a path with source files:
```
Example:
create_javadoc(my_example_doc
PACKAGES com.exmaple.foo com.example.bar
SOURCEPATH "${CMAKE_CURRENT_SOURCE_DIR}"
CLASSPATH ${CMAKE_JAVA_INCLUDE_PATH}
WINDOWTITLE "My example"
DOCTITLE "<h1>My example</h1>"
AUTHOR TRUE
USE TRUE
VERSION TRUE
)
```
The second signature for create\_javadoc works on a given list of files.
```
create_javadoc(<VAR>
FILES file1 [file2 ...]
[CLASSPATH <classpath>]
[INSTALLPATH <install path>]
[DOCTITLE "the documentation title"]
[WINDOWTITLE "the title of the document"]
[AUTHOR TRUE|FALSE]
[USE TRUE|FALSE]
[VERSION TRUE|FALSE]
)
```
Example:
```
create_javadoc(my_example_doc
FILES ${example_SRCS}
CLASSPATH ${CMAKE_JAVA_INCLUDE_PATH}
WINDOWTITLE "My example"
DOCTITLE "<h1>My example</h1>"
AUTHOR TRUE
USE TRUE
VERSION TRUE
)
```
Both signatures share most of the options. These options are the same as what you can find in the javadoc manpage. Please look at the manpage for CLASSPATH, DOCTITLE, WINDOWTITLE, AUTHOR, USE and VERSION.
The documentation will be by default installed to
```
${CMAKE_INSTALL_PREFIX}/share/javadoc/<VAR>
```
if you don’t set the INSTALLPATH.
```
create_javah(TARGET <target>
GENERATED_FILES <VAR>
CLASSES <class>...
[CLASSPATH <classpath>...]
[DEPENDS <depend>...]
[OUTPUT_NAME <path>|OUTPUT_DIR <path>]
)
```
Create C header files from java classes. These files provide the connective glue that allow your Java and C code to interact.
There are two main signatures for create\_javah. The first signature returns generated files through variable specified by GENERATED\_FILES option:
```
Example:
Create_javah(GENERATED_FILES files_headers
CLASSES org.cmake.HelloWorld
CLASSPATH hello.jar
)
```
The second signature for create\_javah creates a target which encapsulates header files generation.
```
Example:
Create_javah(TARGET target_headers
CLASSES org.cmake.HelloWorld
CLASSPATH hello.jar
)
```
Both signatures share same options.
`CLASSES <class>...` Specifies Java classes used to generate headers.
`CLASSPATH <classpath>...` Specifies various paths to look up classes. Here .class files, jar files or targets created by command add\_jar can be used.
`DEPENDS <depend>...` Targets on which the javah target depends
`OUTPUT_NAME <path>` Concatenates the resulting header files for all the classes listed by option CLASSES into <path>. Same behavior as option ‘-o’ of javah tool.
`OUTPUT_DIR <path>` Sets the directory where the header files will be generated. Same behavior as option ‘-d’ of javah tool. If not specified, ${CMAKE\_CURRENT\_BINARY\_DIR} is used as output directory.
cmake TestForSTDNamespace TestForSTDNamespace
===================
Test for std:: namespace support
check if the compiler supports std:: on stl classes
```
CMAKE_NO_STD_NAMESPACE - defined by the results
```
cmake FindCURL FindCURL
========
Find curl
Find the native CURL headers and libraries.
```
CURL_INCLUDE_DIRS - where to find curl/curl.h, etc.
CURL_LIBRARIES - List of libraries when using curl.
CURL_FOUND - True if curl found.
CURL_VERSION_STRING - the version of curl found (since CMake 2.8.8)
```
cmake FindLTTngUST FindLTTngUST
============
This module finds the [LTTng-UST](http://lttng.org/) library.
Imported target
---------------
This module defines the following [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target:
`LTTng::UST` The LTTng-UST library, if found Result variables
----------------
This module sets the following
`LTTNGUST_FOUND`
`TRUE` if system has LTTng-UST
`LTTNGUST_INCLUDE_DIRS` The LTTng-UST include directories
`LTTNGUST_LIBRARIES` The libraries needed to use LTTng-UST
`LTTNGUST_VERSION_STRING` The LTTng-UST version
`LTTNGUST_HAS_TRACEF`
`TRUE` if the `tracef()` API is available in the system’s LTTng-UST
`LTTNGUST_HAS_TRACELOG`
`TRUE` if the `tracelog()` API is available in the system’s LTTng-UST
cmake FindTclsh FindTclsh
=========
Find tclsh
This module finds if TCL is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:
```
TCLSH_FOUND = TRUE if tclsh has been found
TCL_TCLSH = the path to the tclsh executable
```
In cygwin, look for the cygwin version first. Don’t look for it later to avoid finding the cygwin version on a Win32 build.
cmake FortranCInterface FortranCInterface
=================
Fortran/C Interface Detection
This module automatically detects the API by which C and Fortran languages interact.
Module Variables
----------------
Variables that indicate if the mangling is found:
`FortranCInterface_GLOBAL_FOUND` Global subroutines and functions.
`FortranCInterface_MODULE_FOUND` Module subroutines and functions (declared by “MODULE PROCEDURE”). This module also provides the following variables to specify the detected mangling, though a typical use case does not need to reference them and can use the [Module Functions](#module-functions) below.
`FortranCInterface_GLOBAL_PREFIX` Prefix for a global symbol without an underscore.
`FortranCInterface_GLOBAL_SUFFIX` Suffix for a global symbol without an underscore.
`FortranCInterface_GLOBAL_CASE` The case for a global symbol without an underscore, either `UPPER` or `LOWER`.
`FortranCInterface_GLOBAL__PREFIX` Prefix for a global symbol with an underscore.
`FortranCInterface_GLOBAL__SUFFIX` Suffix for a global symbol with an underscore.
`FortranCInterface_GLOBAL__CASE` The case for a global symbol with an underscore, either `UPPER` or `LOWER`.
`FortranCInterface_MODULE_PREFIX` Prefix for a module symbol without an underscore.
`FortranCInterface_MODULE_MIDDLE` Middle of a module symbol without an underscore that appears between the name of the module and the name of the symbol.
`FortranCInterface_MODULE_SUFFIX` Suffix for a module symbol without an underscore.
`FortranCInterface_MODULE_CASE` The case for a module symbol without an underscore, either `UPPER` or `LOWER`.
`FortranCInterface_MODULE__PREFIX` Prefix for a module symbol with an underscore.
`FortranCInterface_MODULE__MIDDLE` Middle of a module symbol with an underscore that appears between the name of the module and the name of the symbol.
`FortranCInterface_MODULE__SUFFIX` Suffix for a module symbol with an underscore.
`FortranCInterface_MODULE__CASE` The case for a module symbol with an underscore, either `UPPER` or `LOWER`. Module Functions
----------------
`FortranCInterface_HEADER`
The `FortranCInterface_HEADER` function is provided to generate a C header file containing macros to mangle symbol names:
```
FortranCInterface_HEADER(<file>
[MACRO_NAMESPACE <macro-ns>]
[SYMBOL_NAMESPACE <ns>]
[SYMBOLS [<module>:]<function> ...])
```
It generates in `<file>` definitions of the following macros:
```
#define FortranCInterface_GLOBAL (name,NAME) ...
#define FortranCInterface_GLOBAL_(name,NAME) ...
#define FortranCInterface_MODULE (mod,name, MOD,NAME) ...
#define FortranCInterface_MODULE_(mod,name, MOD,NAME) ...
```
These macros mangle four categories of Fortran symbols, respectively:
* Global symbols without ‘\_’: `call mysub()`
* Global symbols with ‘\_’ : `call my_sub()`
* Module symbols without ‘\_’: `use mymod; call mysub()`
* Module symbols with ‘\_’ : `use mymod; call my_sub()`
If mangling for a category is not known, its macro is left undefined. All macros require raw names in both lower case and upper case.
The options are:
`MACRO_NAMESPACE` Replace the default `FortranCInterface_` prefix with a given namespace `<macro-ns>`.
`SYMBOLS`
List symbols to mangle automatically with C preprocessor definitions:
```
<function> ==> #define <ns><function> ...
<module>:<function> ==> #define <ns><module>_<function> ...
```
If the mangling for some symbol is not known then no preprocessor definition is created, and a warning is displayed.
`SYMBOL_NAMESPACE` Prefix all preprocessor definitions generated by the `SYMBOLS` option with a given namespace `<ns>`.
`FortranCInterface_VERIFY`
The `FortranCInterface_VERIFY` function is provided to verify that the Fortran and C/C++ compilers work together:
```
FortranCInterface_VERIFY([CXX] [QUIET])
```
It tests whether a simple test executable using Fortran and C (and C++ when the CXX option is given) compiles and links successfully. The result is stored in the cache entry `FortranCInterface_VERIFIED_C` (or `FortranCInterface_VERIFIED_CXX` if `CXX` is given) as a boolean. If the check fails and `QUIET` is not given the function terminates with a fatal error message describing the problem. The purpose of this check is to stop a build early for incompatible compiler combinations. The test is built in the `Release` configuration.
Example Usage
-------------
```
include(FortranCInterface)
FortranCInterface_HEADER(FC.h MACRO_NAMESPACE "FC_")
```
This creates a “FC.h” header that defines mangling macros `FC_GLOBAL()`, `FC_GLOBAL_()`, `FC_MODULE()`, and `FC_MODULE_()`.
```
include(FortranCInterface)
FortranCInterface_HEADER(FCMangle.h
MACRO_NAMESPACE "FC_"
SYMBOL_NAMESPACE "FC_"
SYMBOLS mysub mymod:my_sub)
```
This creates a “FCMangle.h” header that defines the same `FC_*()` mangling macros as the previous example plus preprocessor symbols `FC_mysub` and `FC_mymod_my_sub`.
Additional Manglings
--------------------
FortranCInterface is aware of possible `GLOBAL` and `MODULE` manglings for many Fortran compilers, but it also provides an interface to specify new possible manglings. Set the variables:
```
FortranCInterface_GLOBAL_SYMBOLS
FortranCInterface_MODULE_SYMBOLS
```
before including FortranCInterface to specify manglings of the symbols `MySub`, `My_Sub`, `MyModule:MySub`, and `My_Module:My_Sub`. For example, the code:
```
set(FortranCInterface_GLOBAL_SYMBOLS mysub_ my_sub__ MYSUB_)
# ^^^^^ ^^^^^^ ^^^^^
set(FortranCInterface_MODULE_SYMBOLS
__mymodule_MOD_mysub __my_module_MOD_my_sub)
# ^^^^^^^^ ^^^^^ ^^^^^^^^^ ^^^^^^
include(FortranCInterface)
```
tells FortranCInterface to try given `GLOBAL` and `MODULE` manglings. (The carets point at raw symbol names for clarity in this example but are not needed.)
cmake CSharpUtilities CSharpUtilities
===============
Functions to make configuration of CSharp/.NET targets easier.
A collection of CMake utility functions useful for dealing with CSharp targets for Visual Studio generators from version 2010 and later.
The following functions are provided by this module:
**Main functions**
* [`csharp_set_windows_forms_properties()`](#command:csharp_set_windows_forms_properties "csharp_set_windows_forms_properties")
* [`csharp_set_designer_cs_properties()`](#command:csharp_set_designer_cs_properties "csharp_set_designer_cs_properties")
* [`csharp_set_xaml_cs_properties()`](#command:csharp_set_xaml_cs_properties "csharp_set_xaml_cs_properties")
**Helper functions**
* [`csharp_get_filename_keys()`](#command:csharp_get_filename_keys "csharp_get_filename_keys")
* [`csharp_get_filename_key_base()`](#command:csharp_get_filename_key_base "csharp_get_filename_key_base")
* [`csharp_get_dependentupon_name()`](#command:csharp_get_dependentupon_name "csharp_get_dependentupon_name")
Main functions provided by the module
-------------------------------------
`csharp_set_windows_forms_properties`
Sets source file properties for use of Windows Forms. Use this, if your CSharp target uses Windows Forms:
```
csharp_set_windows_forms_properties([<file1> [<file2> [...]]])
```
`<fileN>` List of all source files which are relevant for setting the [`VS_CSHARP_<tagname>`](# "VS_CSHARP_<tagname>") properties (including `.cs`, `.resx` and `.Designer.cs` extensions). In the list of all given files for all files ending with `.Designer.cs` and `.resx` is searched. For every *designer* or *resource* file a file with the same base name but only `.cs` as extension is searched. If this is found, the [`VS_CSHARP_<tagname>`](# "VS_CSHARP_<tagname>") properties are set as follows:
for the **.cs** file:
* VS\_CSHARP\_SubType “Form”
for the **.Designer.cs** file (if it exists):
* VS\_CSHARP\_DependentUpon <cs-filename>
* VS\_CSHARP\_DesignTime “” (delete tag if previously defined)
* VS\_CSHARP\_AutoGen “”(delete tag if previously defined)
for the **.resx** file (if it exists):
* VS\_RESOURCE\_GENERATOR “” (delete tag if previously defined)
* VS\_CSHARP\_DependentUpon <cs-filename>
* VS\_CSHARP\_SubType “Designer”
`csharp_set_designer_cs_properties`
Sets source file properties of `.Designer.cs` files depending on sibling filenames. Use this, if your CSharp target does **not** use Windows Forms (for Windows Forms use [`csharp_set_designer_cs_properties()`](#command:csharp_set_designer_cs_properties "csharp_set_designer_cs_properties") instead):
```
csharp_set_designer_cs_properties([<file1> [<file2> [...]]])
```
`<fileN>` List of all source files which are relevant for setting the [`VS_CSHARP_<tagname>`](# "VS_CSHARP_<tagname>") properties (including `.cs`, `.resx`, `.settings` and `.Designer.cs` extensions). In the list of all given files for all files ending with `.Designer.cs` is searched. For every *designer* file all files with the same base name but different extensions are searched. If a match is found, the source file properties of the *designer* file are set depending on the extension of the matched file:
if match is **.resx** file:
* VS\_CSHARP\_AutoGen “True”
* VS\_CSHARP\_DesignTime “True”
* VS\_CSHARP\_DependentUpon <resx-filename>
if match is **.cs** file:
* VS\_CSHARP\_DependentUpon <cs-filename>
if match is **.settings** file:
* VS\_CSHARP\_AutoGen “True”
* VS\_CSHARP\_DesignTimeSharedInput “True”
* VS\_CSHARP\_DependentUpon <settings-filename>
Note
Because the source file properties of the `.Designer.cs` file are set according to the found matches and every match sets the **VS\_CSHARP\_DependentUpon** property, there should only be one match for each `Designer.cs` file.
`csharp_set_xaml_cs_properties`
Sets source file properties for use of Windows Presentation Foundation (WPF) and XAML. Use this, if your CSharp target uses WPF/XAML:
```
csharp_set_xaml_cs_properties([<file1> [<file2> [...]]])
```
`<fileN>` List of all source files which are relevant for setting the [`VS_CSHARP_<tagname>`](# "VS_CSHARP_<tagname>") properties (including `.cs`, `.xaml`, and `.xaml.cs` extensions). In the list of all given files for all files ending with `.xaml.cs` is searched. For every *xaml-cs* file, a file with the same base name but extension `.xaml` is searched. If a match is found, the source file properties of the `.xaml.cs` file are set:
* VS\_CSHARP\_DependentUpon <xaml-filename>
Helper functions which are used by the above ones
-------------------------------------------------
`csharp_get_filename_keys`
Helper function which computes a list of key values to identify source files independently of relative/absolute paths given in cmake and eliminates case sensitivity:
```
csharp_get_filename_keys(OUT [<file1> [<file2> [...]]])
```
`OUT` Name of the variable in which the list of keys is stored
`<fileN>` filename(s) as given to to CSharp target using [`add_library()`](../command/add_library#command:add_library "add_library") or [`add_executable()`](../command/add_executable#command:add_executable "add_executable")
In some way the function applies a canonicalization to the source names. This is necessary to find file matches if the files have been added to the target with different directory prefixes:
```
add_library(lib
myfile.cs
${CMAKE_CURRENT_SOURCE_DIR}/myfile.Designer.cs)
set_source_files_properties(myfile.Designer.cs PROPERTIES
VS_CSHARP_DependentUpon myfile.cs)
# this will fail, because in cmake
# - ${CMAKE_CURRENT_SOURCE_DIR}/myfile.Designer.cs
# - myfile.Designer.cs
# are not the same source file. The source file property is not set.
```
`csharp_get_filename_key_base`
Returns the full filepath and name **without** extension of a key. KEY is expected to be a key from csharp\_get\_filename\_keys. In BASE the value of KEY without the file extension is returned:
```
csharp_get_filename_key_base(BASE KEY)
```
`BASE` Name of the variable with the computed “base” of `KEY`.
`KEY` The key of which the base will be computed. Expected to be a upper case full filename.
`csharp_get_dependentupon_name`
Computes a string which can be used as value for the source file property [`VS_CSHARP_<tagname>`](# "VS_CSHARP_<tagname>") with *target* being `DependentUpon`:
```
csharp_get_dependentupon_name(NAME FILE)
```
`NAME` Name of the variable with the result value
`FILE` Filename to convert to `<DependentUpon>` value Actually this is only the filename without any path given at the moment.
| programming_docs |
cmake FindOpenGL FindOpenGL
==========
FindModule for OpenGL and GLU.
IMPORTED Targets
----------------
This module defines the [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets:
`OpenGL::GL` Defined if the system has OpenGL.
`OpenGL::GLU` Defined if the system has GLU. Result Variables
----------------
This module sets the following variables:
`OPENGL_FOUND` True, if the system has OpenGL.
`OPENGL_XMESA_FOUND` True, if the system has XMESA.
`OPENGL_GLU_FOUND` True, if the system has GLU.
`OPENGL_INCLUDE_DIR` Path to the OpenGL include directory.
`OPENGL_LIBRARIES` Paths to the OpenGL and GLU libraries. If you want to use just GL you can use these values:
`OPENGL_gl_LIBRARY` Path to the OpenGL library.
`OPENGL_glu_LIBRARY` Path to the GLU library. OSX Specific
------------
On OSX default to using the framework version of OpenGL. People will have to change the cache values of OPENGL\_glu\_LIBRARY and OPENGL\_gl\_LIBRARY to use OpenGL with X11 on OSX.
cmake FindSDL_sound FindSDL\_sound
==============
Locates the SDL\_sound library
This module depends on SDL being found and must be called AFTER FindSDL.cmake is called.
This module defines
```
SDL_SOUND_INCLUDE_DIR, where to find SDL_sound.h
SDL_SOUND_FOUND, if false, do not try to link to SDL_sound
SDL_SOUND_LIBRARIES, this contains the list of libraries that you need
to link against.
SDL_SOUND_EXTRAS, this is an optional variable for you to add your own
flags to SDL_SOUND_LIBRARIES. This is prepended to SDL_SOUND_LIBRARIES.
This is available mostly for cases this module failed to anticipate for
and you must add additional flags. This is marked as ADVANCED.
SDL_SOUND_VERSION_STRING, human-readable string containing the
version of SDL_sound
```
This module also defines (but you shouldn’t need to use directly)
```
SDL_SOUND_LIBRARY, the name of just the SDL_sound library you would link
against. Use SDL_SOUND_LIBRARIES for you link instructions and not this one.
```
And might define the following as needed
```
MIKMOD_LIBRARY
MODPLUG_LIBRARY
OGG_LIBRARY
VORBIS_LIBRARY
SMPEG_LIBRARY
FLAC_LIBRARY
SPEEX_LIBRARY
```
Typically, you should not use these variables directly, and you should use SDL\_SOUND\_LIBRARIES which contains SDL\_SOUND\_LIBRARY and the other audio libraries (if needed) to successfully compile on your system.
Created by Eric Wing. This module is a bit more complicated than the other FindSDL\* family modules. The reason is that SDL\_sound can be compiled in a large variety of different ways which are independent of platform. SDL\_sound may dynamically link against other 3rd party libraries to get additional codec support, such as Ogg Vorbis, SMPEG, ModPlug, MikMod, FLAC, Speex, and potentially others. Under some circumstances which I don’t fully understand, there seems to be a requirement that dependent libraries of libraries you use must also be explicitly linked against in order to successfully compile. SDL\_sound does not currently have any system in place to know how it was compiled. So this CMake module does the hard work in trying to discover which 3rd party libraries are required for building (if any). This module uses a brute force approach to create a test program that uses SDL\_sound, and then tries to build it. If the build fails, it parses the error output for known symbol names to figure out which libraries are needed.
Responds to the $SDLDIR and $SDLSOUNDDIR environmental variable that would correspond to the ./configure –prefix=$SDLDIR used in building SDL.
On OSX, this will prefer the Framework version (if found) over others. People will have to manually change the cache values of SDL\_LIBRARY to override this selectionor set the CMake environment CMAKE\_INCLUDE\_PATH to modify the search paths.
cmake FindJava FindJava
========
Find Java
This module finds if Java is installed and determines where the include files and libraries are. The caller may set variable JAVA\_HOME to specify a Java installation prefix explicitly.
See also the [`FindJNI`](findjni#module:FindJNI "FindJNI") module to find Java development tools.
Specify one or more of the following components as you call this find module. See example below.
```
Runtime = User just want to execute some Java byte-compiled
Development = Development tools (java, javac, javah and javadoc), includes Runtime component
IdlJ = idl compiler for Java
JarSigner = signer tool for jar
```
This module sets the following result variables:
```
Java_JAVA_EXECUTABLE = the full path to the Java runtime
Java_JAVAC_EXECUTABLE = the full path to the Java compiler
Java_JAVAH_EXECUTABLE = the full path to the Java header generator
Java_JAVADOC_EXECUTABLE = the full path to the Java documentation generator
Java_IDLJ_EXECUTABLE = the full path to the Java idl compiler
Java_JAR_EXECUTABLE = the full path to the Java archiver
Java_JARSIGNER_EXECUTABLE = the full path to the Java jar signer
Java_VERSION_STRING = Version of java found, eg. 1.6.0_12
Java_VERSION_MAJOR = The major version of the package found.
Java_VERSION_MINOR = The minor version of the package found.
Java_VERSION_PATCH = The patch version of the package found.
Java_VERSION_TWEAK = The tweak version of the package found (after '_')
Java_VERSION = This is set to: $major.$minor.$patch(.$tweak)
```
The minimum required version of Java can be specified using the standard CMake syntax, e.g. find\_package(Java 1.5)
NOTE: ${Java\_VERSION} and ${Java\_VERSION\_STRING} are not guaranteed to be identical. For example some java version may return: Java\_VERSION\_STRING = 1.5.0\_17 and Java\_VERSION = 1.5.0.17
another example is the Java OEM, with: Java\_VERSION\_STRING = 1.6.0-oem and Java\_VERSION = 1.6.0
For these components the following variables are set:
```
Java_FOUND - TRUE if all components are found.
Java_<component>_FOUND - TRUE if <component> is found.
```
Example Usages:
```
find_package(Java)
find_package(Java COMPONENTS Runtime)
find_package(Java COMPONENTS Development)
```
cmake GetPrerequisites GetPrerequisites
================
Functions to analyze and list executable file prerequisites.
This module provides functions to list the .dll, .dylib or .so files that an executable or shared library file depends on. (Its prerequisites.)
It uses various tools to obtain the list of required shared library files:
```
dumpbin (Windows)
objdump (MinGW on Windows)
ldd (Linux/Unix)
otool (Mac OSX)
```
The following functions are provided by this module:
```
get_prerequisites
list_prerequisites
list_prerequisites_by_glob
gp_append_unique
is_file_executable
gp_item_default_embedded_path
(projects can override with gp_item_default_embedded_path_override)
gp_resolve_item
(projects can override with gp_resolve_item_override)
gp_resolved_file_type
(projects can override with gp_resolved_file_type_override)
gp_file_type
```
Requires CMake 2.6 or greater because it uses function, break, return and PARENT\_SCOPE.
```
GET_PREREQUISITES(<target> <prerequisites_var> <exclude_system> <recurse>
<exepath> <dirs> [<rpaths>])
```
Get the list of shared library files required by <target>. The list in the variable named <prerequisites\_var> should be empty on first entry to this function. On exit, <prerequisites\_var> will contain the list of required shared library files.
<target> is the full path to an executable file. <prerequisites\_var> is the name of a CMake variable to contain the results. <exclude\_system> must be 0 or 1 indicating whether to include or exclude “system” prerequisites. If <recurse> is set to 1 all prerequisites will be found recursively, if set to 0 only direct prerequisites are listed. <exepath> is the path to the top level executable used for @executable\_path replacment on the Mac. <dirs> is a list of paths where libraries might be found: these paths are searched first when a target without any path info is given. Then standard system locations are also searched: PATH, Framework locations, /usr/lib…
```
LIST_PREREQUISITES(<target> [<recurse> [<exclude_system> [<verbose>]]])
```
Print a message listing the prerequisites of <target>.
<target> is the name of a shared library or executable target or the full path to a shared library or executable file. If <recurse> is set to 1 all prerequisites will be found recursively, if set to 0 only direct prerequisites are listed. <exclude\_system> must be 0 or 1 indicating whether to include or exclude “system” prerequisites. With <verbose> set to 0 only the full path names of the prerequisites are printed, set to 1 extra informatin will be displayed.
```
LIST_PREREQUISITES_BY_GLOB(<glob_arg> <glob_exp>)
```
Print the prerequisites of shared library and executable files matching a globbing pattern. <glob\_arg> is GLOB or GLOB\_RECURSE and <glob\_exp> is a globbing expression used with “file(GLOB” or “file(GLOB\_RECURSE” to retrieve a list of matching files. If a matching file is executable, its prerequisites are listed.
Any additional (optional) arguments provided are passed along as the optional arguments to the list\_prerequisites calls.
```
GP_APPEND_UNIQUE(<list_var> <value>)
```
Append <value> to the list variable <list\_var> only if the value is not already in the list.
```
IS_FILE_EXECUTABLE(<file> <result_var>)
```
Return 1 in <result\_var> if <file> is a binary executable, 0 otherwise.
```
GP_ITEM_DEFAULT_EMBEDDED_PATH(<item> <default_embedded_path_var>)
```
Return the path that others should refer to the item by when the item is embedded inside a bundle.
Override on a per-project basis by providing a project-specific gp\_item\_default\_embedded\_path\_override function.
```
GP_RESOLVE_ITEM(<context> <item> <exepath> <dirs> <resolved_item_var>
[<rpaths>])
```
Resolve an item into an existing full path file.
Override on a per-project basis by providing a project-specific gp\_resolve\_item\_override function.
```
GP_RESOLVED_FILE_TYPE(<original_file> <file> <exepath> <dirs> <type_var>
[<rpaths>])
```
Return the type of <file> with respect to <original\_file>. String describing type of prerequisite is returned in variable named <type\_var>.
Use <exepath> and <dirs> if necessary to resolve non-absolute <file> values – but only for non-embedded items.
Possible types are:
```
system
local
embedded
other
```
Override on a per-project basis by providing a project-specific gp\_resolved\_file\_type\_override function.
```
GP_FILE_TYPE(<original_file> <file> <type_var>)
```
Return the type of <file> with respect to <original\_file>. String describing type of prerequisite is returned in variable named <type\_var>.
Possible types are:
```
system
local
embedded
other
```
cmake CMakeFindDependencyMacro CMakeFindDependencyMacro
========================
```
find_dependency(<dep> [...])
```
`find_dependency()` wraps a [`find_package()`](../command/find_package#command:find_package "find_package") call for a package dependency. It is designed to be used in a <package>Config.cmake file, and it forwards the correct parameters for QUIET and REQUIRED which were passed to the original [`find_package()`](../command/find_package#command:find_package "find_package") call. It also sets an informative diagnostic message if the dependency could not be found.
Any additional arguments specified are forwarded to [`find_package()`](../command/find_package#command:find_package "find_package").
cmake FindGLUT FindGLUT
========
try to find glut library and include files.
IMPORTED Targets
----------------
This module defines the [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets:
`GLUT::GLUT` Defined if the system has GLUT. Result Variables
----------------
This module sets the following variables:
```
GLUT_INCLUDE_DIR, where to find GL/glut.h, etc.
GLUT_LIBRARIES, the libraries to link against
GLUT_FOUND, If false, do not try to use GLUT.
```
Also defined, but not for general use are:
```
GLUT_glut_LIBRARY = the full path to the glut library.
GLUT_Xmu_LIBRARY = the full path to the Xmu library.
GLUT_Xi_LIBRARY = the full path to the Xi Library.
```
cmake CMakeVerifyManifest CMakeVerifyManifest
===================
CMakeVerifyManifest.cmake
This script is used to verify that embedded manifests and side by side manifests for a project match. To run this script, cd to a directory and run the script with cmake -P. On the command line you can pass in versions that are OK even if not found in the .manifest files. For example, cmake -Dallow\_versions=8.0.50608.0 -PCmakeVerifyManifest.cmake could be used to allow an embedded manifest of 8.0.50608.0 to be used in a project even if that version was not found in the .manifest file.
cmake FindOpenThreads FindOpenThreads
===============
OpenThreads is a C++ based threading library. Its largest userbase seems to OpenSceneGraph so you might notice I accept OSGDIR as an environment path. I consider this part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module.
Locate OpenThreads This module defines OPENTHREADS\_LIBRARY OPENTHREADS\_FOUND, if false, do not try to link to OpenThreads OPENTHREADS\_INCLUDE\_DIR, where to find the headers
$OPENTHREADS\_DIR is an environment variable that would correspond to the ./configure –prefix=$OPENTHREADS\_DIR used in building osg.
[CMake 2.8.10]: The CMake variables OPENTHREADS\_DIR or OSG\_DIR can now be used as well to influence detection, instead of needing to specify an environment variable.
Created by Eric Wing.
cmake FindGSL FindGSL
=======
Find the native GSL includes and libraries.
The GNU Scientific Library (GSL) is a numerical library for C and C++ programmers. It is free software under the GNU General Public License.
Imported Targets
----------------
If GSL is found, this module defines the following [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets:
```
GSL::gsl - The main GSL library.
GSL::gslcblas - The CBLAS support library used by GSL.
```
Result Variables
----------------
This module will set the following variables in your project:
```
GSL_FOUND - True if GSL found on the local system
GSL_INCLUDE_DIRS - Location of GSL header files.
GSL_LIBRARIES - The GSL libraries.
GSL_VERSION - The version of the discovered GSL install.
```
Hints
-----
Set `GSL_ROOT_DIR` to a directory that contains a GSL installation.
This script expects to find libraries at `$GSL_ROOT_DIR/lib` and the GSL headers at `$GSL_ROOT_DIR/include/gsl`. The library directory may optionally provide Release and Debug folders. If available, the libraries named `gsld`, `gslblasd` or `cblasd` are recognized as debug libraries. For Unix-like systems, this script will use `$GSL_ROOT_DIR/bin/gsl-config` (if found) to aid in the discovery of GSL.
Cache Variables
---------------
This module may set the following variables depending on platform and type of GSL installation discovered. These variables may optionally be set to help this module find the correct files:
```
GSL_CBLAS_LIBRARY - Location of the GSL CBLAS library.
GSL_CBLAS_LIBRARY_DEBUG - Location of the debug GSL CBLAS library (if any).
GSL_CONFIG_EXECUTABLE - Location of the ``gsl-config`` script (if any).
GSL_LIBRARY - Location of the GSL library.
GSL_LIBRARY_DEBUG - Location of the debug GSL library (if any).
```
cmake GenerateExportHeader GenerateExportHeader
====================
Function for generation of export macros for libraries
This module provides the function GENERATE\_EXPORT\_HEADER().
The `GENERATE_EXPORT_HEADER` function can be used to generate a file suitable for preprocessor inclusion which contains EXPORT macros to be used in library classes:
```
GENERATE_EXPORT_HEADER( LIBRARY_TARGET
[BASE_NAME <base_name>]
[EXPORT_MACRO_NAME <export_macro_name>]
[EXPORT_FILE_NAME <export_file_name>]
[DEPRECATED_MACRO_NAME <deprecated_macro_name>]
[NO_EXPORT_MACRO_NAME <no_export_macro_name>]
[STATIC_DEFINE <static_define>]
[NO_DEPRECATED_MACRO_NAME <no_deprecated_macro_name>]
[DEFINE_NO_DEPRECATED]
[PREFIX_NAME <prefix_name>]
[CUSTOM_CONTENT_FROM_VARIABLE <variable>]
)
```
The target properties [`CXX_VISIBILITY_PRESET`](# "<LANG>_VISIBILITY_PRESET") and [`VISIBILITY_INLINES_HIDDEN`](../prop_tgt/visibility_inlines_hidden#prop_tgt:VISIBILITY_INLINES_HIDDEN "VISIBILITY_INLINES_HIDDEN") can be used to add the appropriate compile flags for targets. See the documentation of those target properties, and the convenience variables [`CMAKE_CXX_VISIBILITY_PRESET`](# "CMAKE_<LANG>_VISIBILITY_PRESET") and [`CMAKE_VISIBILITY_INLINES_HIDDEN`](../variable/cmake_visibility_inlines_hidden#variable:CMAKE_VISIBILITY_INLINES_HIDDEN "CMAKE_VISIBILITY_INLINES_HIDDEN").
By default `GENERATE_EXPORT_HEADER()` generates macro names in a file name determined by the name of the library. This means that in the simplest case, users of `GenerateExportHeader` will be equivalent to:
```
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
add_library(somelib someclass.cpp)
generate_export_header(somelib)
install(TARGETS somelib DESTINATION ${LIBRARY_INSTALL_DIR})
install(FILES
someclass.h
${PROJECT_BINARY_DIR}/somelib_export.h DESTINATION ${INCLUDE_INSTALL_DIR}
)
```
And in the ABI header files:
```
#include "somelib_export.h"
class SOMELIB_EXPORT SomeClass {
...
};
```
The CMake fragment will generate a file in the `${CMAKE_CURRENT_BINARY_DIR}` called `somelib_export.h` containing the macros `SOMELIB_EXPORT`, `SOMELIB_NO_EXPORT`, `SOMELIB_DEPRECATED`, `SOMELIB_DEPRECATED_EXPORT` and `SOMELIB_DEPRECATED_NO_EXPORT`. They will be followed by content taken from the variable specified by the `CUSTOM_CONTENT_FROM_VARIABLE` option, if any. The resulting file should be installed with other headers in the library.
The `BASE_NAME` argument can be used to override the file name and the names used for the macros:
```
add_library(somelib someclass.cpp)
generate_export_header(somelib
BASE_NAME other_name
)
```
Generates a file called `other_name_export.h` containing the macros `OTHER_NAME_EXPORT`, `OTHER_NAME_NO_EXPORT` and `OTHER_NAME_DEPRECATED` etc.
The `BASE_NAME` may be overridden by specifying other options in the function. For example:
```
add_library(somelib someclass.cpp)
generate_export_header(somelib
EXPORT_MACRO_NAME OTHER_NAME_EXPORT
)
```
creates the macro `OTHER_NAME_EXPORT` instead of `SOMELIB_EXPORT`, but other macros and the generated file name is as default:
```
add_library(somelib someclass.cpp)
generate_export_header(somelib
DEPRECATED_MACRO_NAME KDE_DEPRECATED
)
```
creates the macro `KDE_DEPRECATED` instead of `SOMELIB_DEPRECATED`.
If `LIBRARY_TARGET` is a static library, macros are defined without values.
If the same sources are used to create both a shared and a static library, the uppercased symbol `${BASE_NAME}_STATIC_DEFINE` should be used when building the static library:
```
add_library(shared_variant SHARED ${lib_SRCS})
add_library(static_variant ${lib_SRCS})
generate_export_header(shared_variant BASE_NAME libshared_and_static)
set_target_properties(static_variant PROPERTIES
COMPILE_FLAGS -DLIBSHARED_AND_STATIC_STATIC_DEFINE)
```
This will cause the export macros to expand to nothing when building the static library.
If `DEFINE_NO_DEPRECATED` is specified, then a macro `${BASE_NAME}_NO_DEPRECATED` will be defined This macro can be used to remove deprecated code from preprocessor output:
```
option(EXCLUDE_DEPRECATED "Exclude deprecated parts of the library" FALSE)
if (EXCLUDE_DEPRECATED)
set(NO_BUILD_DEPRECATED DEFINE_NO_DEPRECATED)
endif()
generate_export_header(somelib ${NO_BUILD_DEPRECATED})
```
And then in somelib:
```
class SOMELIB_EXPORT SomeClass
{
public:
#ifndef SOMELIB_NO_DEPRECATED
SOMELIB_DEPRECATED void oldMethod();
#endif
};
```
```
#ifndef SOMELIB_NO_DEPRECATED
void SomeClass::oldMethod() { }
#endif
```
If `PREFIX_NAME` is specified, the argument will be used as a prefix to all generated macros.
For example:
```
generate_export_header(somelib PREFIX_NAME VTK_)
```
Generates the macros `VTK_SOMELIB_EXPORT` etc.
```
ADD_COMPILER_EXPORT_FLAGS( [<output_variable>] )
```
The `ADD_COMPILER_EXPORT_FLAGS` function adds `-fvisibility=hidden` to [`CMAKE_CXX_FLAGS`](# "CMAKE_<LANG>_FLAGS") if supported, and is a no-op on Windows which does not need extra compiler flags for exporting support. You may optionally pass a single argument to `ADD_COMPILER_EXPORT_FLAGS` that will be populated with the `CXX_FLAGS` required to enable visibility support for the compiler/architecture in use.
This function is deprecated. Set the target properties [`CXX_VISIBILITY_PRESET`](# "<LANG>_VISIBILITY_PRESET") and [`VISIBILITY_INLINES_HIDDEN`](../prop_tgt/visibility_inlines_hidden#prop_tgt:VISIBILITY_INLINES_HIDDEN "VISIBILITY_INLINES_HIDDEN") instead.
| programming_docs |
cmake FindDoxygen FindDoxygen
===========
Doxygen is a documentation generation tool (see <http://www.doxygen.org>). This module looks for Doxygen and some optional tools it supports. These tools are enabled as components in the [`find_package()`](../command/find_package#command:find_package "find_package") command:
`dot`
[Graphviz](http://graphviz.org) `dot` utility used to render various graphs.
`mscgen`
[Message Chart Generator](http://www.mcternan.me.uk/mscgen/) utility used by Doxygen’s `\msc` and `\mscfile` commands.
`dia`
[Dia](https://wiki.gnome.org/Apps/Dia) the diagram editor used by Doxygen’s `\diafile` command. Examples:
```
# Require dot, treat the other components as optional
find_package(Doxygen
REQUIRED dot
OPTIONAL_COMPONENTS mscgen dia)
```
The following variables are defined by this module:
`DOXYGEN_FOUND`
True if the `doxygen` executable was found.
`DOXYGEN_VERSION`
The version reported by `doxygen --version`.
The module defines `IMPORTED` targets for Doxygen and each component found. These can be used as part of custom commands, etc. and should be preferred over old-style (and now deprecated) variables like `DOXYGEN_EXECUTABLE`. The following import targets are defined if their corresponding executable could be found (the component import targets will only be defined if that component was requested):
```
Doxygen::doxygen
Doxygen::dot
Doxygen::mscgen
Doxygen::dia
```
Functions
---------
`doxygen_add_docs`
This function is intended as a convenience for adding a target for generating documentation with Doxygen. It aims to provide sensible defaults so that projects can generally just provide the input files and directories and that will be sufficient to give sensible results. The function supports the ability to customize the Doxygen configuration used to build the documentation.
```
doxygen_add_docs(targetName
[filesOrDirs...]
[WORKING_DIRECTORY dir]
[COMMENT comment])
```
The function constructs a `Doxyfile` and defines a custom target that runs Doxygen on that generated file. The listed files and directories are used as the `INPUT` of the generated `Doxyfile` and they can contain wildcards. Any files that are listed explicitly will also be added as `SOURCES` of the custom target so they will show up in an IDE project’s source list.
So that relative input paths work as expected, by default the working directory of the Doxygen command will be the current source directory (i.e. [`CMAKE_CURRENT_SOURCE_DIR`](../variable/cmake_current_source_dir#variable:CMAKE_CURRENT_SOURCE_DIR "CMAKE_CURRENT_SOURCE_DIR")). This can be overridden with the `WORKING_DIRECTORY` option to change the directory used as the relative base point. Note also that Doxygen’s default behavior is to strip the working directory from relative paths in the generated documentation (see the `STRIP_FROM_PATH` [Doxygen config option](http://www.doxygen.org/manual/config.html) for details).
If provided, the optional `comment` will be passed as the `COMMENT` for the [`add_custom_target()`](../command/add_custom_target#command:add_custom_target "add_custom_target") command used to create the custom target internally.
The contents of the generated `Doxyfile` can be customized by setting CMake variables before calling `doxygen_add_docs()`. Any variable with a name of the form `DOXYGEN_<tag>` will have its value substituted for the corresponding `<tag>` configuration option in the `Doxyfile`. See the [Doxygen documentation](http://www.doxygen.org/manual/config.html) for the full list of supported configuration options.
Some of Doxygen’s defaults are overridden to provide more appropriate behavior for a CMake project. Each of the following will be explicitly set unless the variable already has a value before `doxygen_add_docs()` is called (with some exceptions noted):
`DOXYGEN_HAVE_DOT`
Set to `YES` if the `dot` component was requested and it was found, `NO` otherwise. Any existing value of `DOXYGEN_HAVE_DOT` is ignored.
`DOXYGEN_DOT_MULTI_TARGETS`
Set to `YES` by this module (note that this requires a `dot` version newer than 1.8.10). This option is only meaningful if `DOXYGEN_HAVE_DOT` is also set to `YES`.
`DOXYGEN_GENERATE_LATEX`
Set to `NO` by this module.
`DOXYGEN_WARN_FORMAT`
For Visual Studio based generators, this is set to the form recognized by the Visual Studio IDE: `$file($line) : $text`. For all other generators, Doxygen’s default value is not overridden.
`DOXYGEN_PROJECT_NAME`
Populated with the name of the current project (i.e. [`PROJECT_NAME`](../variable/project_name#variable:PROJECT_NAME "PROJECT_NAME")).
`DOXYGEN_PROJECT_NUMBER`
Populated with the version of the current project (i.e. [`PROJECT_VERSION`](../variable/project_version#variable:PROJECT_VERSION "PROJECT_VERSION")).
`DOXYGEN_PROJECT_BRIEF`
Populated with the description of the current project (i.e. [`PROJECT_DESCRIPTION`](../variable/project_description#variable:PROJECT_DESCRIPTION "PROJECT_DESCRIPTION")).
`DOXYGEN_INPUT`
Projects should not set this variable. It will be populated with the set of files and directories passed to `doxygen_add_docs()`, thereby providing consistent behavior with the other built-in commands like [`add_executable()`](../command/add_executable#command:add_executable "add_executable"), [`add_library()`](../command/add_library#command:add_library "add_library") and [`add_custom_target()`](../command/add_custom_target#command:add_custom_target "add_custom_target"). If a variable named `DOXYGEN_INPUT` is set by the project, it will be ignored and a warning will be issued.
`DOXYGEN_RECURSIVE`
Set to `YES` by this module.
`DOXYGEN_EXCLUDE_PATTERNS`
If the set of inputs includes directories, this variable will specify patterns used to exclude files from them. The following patterns are added by `doxygen_add_docs()` to ensure CMake-specific files and directories are not included in the input. If the project sets `DOXYGEN_EXCLUDE_PATTERNS`, those contents are merged with these additional patterns rather than replacing them:
```
*/.git/*
*/.svn/*
*/.hg/*
*/CMakeFiles/*
*/_CPack_Packages/*
DartConfiguration.tcl
CMakeLists.txt
CMakeCache.txt
```
`DOXYGEN_OUTPUT_DIRECTORY`
Set to [`CMAKE_CURRENT_BINARY_DIR`](../variable/cmake_current_binary_dir#variable:CMAKE_CURRENT_BINARY_DIR "CMAKE_CURRENT_BINARY_DIR") by this module. Note that if the project provides its own value for this and it is a relative path, it will be converted to an absolute path relative to the current binary directory. This is necessary because doxygen will normally be run from a directory within the source tree so that relative source paths work as expected. If this directory does not exist, it will be recursively created prior to executing the doxygen commands.
To change any of these defaults or override any other Doxygen config option, set relevant variables before calling `doxygen_add_docs()`. For example:
```
set(DOXYGEN_GENERATE_HTML NO)
set(DOXYGEN_GENERATE_MAN YES)
doxygen_add_docs(
doxygen
${PROJECT_SOURCE_DIR}
COMMENT "Generate man pages"
)
```
A number of Doxygen config options accept lists of values, but Doxygen requires them to be separated by whitespace. CMake variables hold lists as a string with items separated by semi-colons, so a conversion needs to be performed. The `doxygen_add_docs()` command specifically checks the following Doxygen config options and will convert their associated CMake variable’s contents into the required form if set.
```
ABBREVIATE_BRIEF
ALIASES
CITE_BIB_FILES
DIAFILE_DIRS
DOTFILE_DIRS
DOT_FONTPATH
ENABLED_SECTIONS
EXAMPLE_PATH
EXAMPLE_PATTERNS
EXCLUDE
EXCLUDE_PATTERNS
EXCLUDE_SYMBOLS
EXPAND_AS_DEFINED
EXTENSION_MAPPING
EXTRA_PACKAGES
EXTRA_SEARCH_MAPPINGS
FILE_PATTERNS
FILTER_PATTERNS
FILTER_SOURCE_PATTERNS
HTML_EXTRA_FILES
HTML_EXTRA_STYLESHEET
IGNORE_PREFIX
IMAGE_PATH
INCLUDE_FILE_PATTERNS
INCLUDE_PATH
INPUT
LATEX_EXTRA_FILES
LATEX_EXTRA_STYLESHEET
MATHJAX_EXTENSIONS
MSCFILE_DIRS
PLANTUML_INCLUDE_PATH
PREDEFINED
QHP_CUST_FILTER_ATTRS
QHP_SECT_FILTER_ATTRS
STRIP_FROM_INC_PATH
STRIP_FROM_PATH
TAGFILES
TCL_SUBST
```
The following single value Doxygen options would be quoted automatically if they contain at least one space:
```
CHM_FILE
DIA_PATH
DOCBOOK_OUTPUT
DOCSET_FEEDNAME
DOCSET_PUBLISHER_NAME
DOT_FONTNAME
DOT_PATH
EXTERNAL_SEARCH_ID
FILE_VERSION_FILTER
GENERATE_TAGFILE
HHC_LOCATION
HTML_FOOTER
HTML_HEADER
HTML_OUTPUT
HTML_STYLESHEET
INPUT_FILTER
LATEX_FOOTER
LATEX_HEADER
LATEX_OUTPUT
LAYOUT_FILE
MAN_OUTPUT
MAN_SUBDIR
MATHJAX_CODEFILE
MSCGEN_PATH
OUTPUT_DIRECTORY
PERL_PATH
PLANTUML_JAR_PATH
PROJECT_BRIEF
PROJECT_LOGO
PROJECT_NAME
QCH_FILE
QHG_LOCATION
QHP_CUST_FILTER_NAME
QHP_VIRTUAL_FOLDER
RTF_EXTENSIONS_FILE
RTF_OUTPUT
RTF_STYLESHEET_FILE
SEARCHDATA_FILE
USE_MDFILE_AS_MAINPAGE
WARN_FORMAT
WARN_LOGFILE
XML_OUTPUT
```
Deprecated Result Variables
---------------------------
For compatibility with previous versions of CMake, the following variables are also defined but they are deprecated and should no longer be used:
`DOXYGEN_EXECUTABLE`
The path to the `doxygen` command. If projects need to refer to the `doxygen` executable directly, they should use the `Doxygen::doxygen` import target instead.
`DOXYGEN_DOT_FOUND`
True if the `dot` executable was found.
`DOXYGEN_DOT_EXECUTABLE`
The path to the `dot` command. If projects need to refer to the `dot` executable directly, they should use the `Doxygen::dot` import target instead.
`DOXYGEN_DOT_PATH`
The path to the directory containing the `dot` executable as reported in `DOXYGEN_DOT_EXECUTABLE`. The path may have forward slashes even on Windows and is not suitable for direct substitution into a `Doxyfile.in` template. If you need this value, get the [`IMPORTED_LOCATION`](../prop_tgt/imported_location#prop_tgt:IMPORTED_LOCATION "IMPORTED_LOCATION") property of the `Doxygen::dot` target and use [`get_filename_component()`](../command/get_filename_component#command:get_filename_component "get_filename_component") to extract the directory part of that path. You may also want to consider using [`file(TO_NATIVE_PATH)`](../command/file#command:file "file") to prepare the path for a Doxygen configuration file.
Deprecated Hint Variables
-------------------------
`DOXYGEN_SKIP_DOT`
This variable has no any effect for component form of `find_package`. In backward compatibility mode (i.e. without components list) it prevents the finder module from searching for Graphviz’s `dot` utility.
cmake FindGTK FindGTK
=======
try to find GTK (and glib) and GTKGLArea
```
GTK_INCLUDE_DIR - Directories to include to use GTK
GTK_LIBRARIES - Files to link against to use GTK
GTK_FOUND - GTK was found
GTK_GL_FOUND - GTK's GL features were found
```
cmake FindJNI FindJNI
=======
Find JNI java libraries.
This module finds if Java is installed and determines where the include files and libraries are. It also determines what the name of the library is. The caller may set variable JAVA\_HOME to specify a Java installation prefix explicitly.
This module sets the following result variables:
```
JNI_INCLUDE_DIRS = the include dirs to use
JNI_LIBRARIES = the libraries to use
JNI_FOUND = TRUE if JNI headers and libraries were found.
JAVA_AWT_LIBRARY = the path to the jawt library
JAVA_JVM_LIBRARY = the path to the jvm library
JAVA_INCLUDE_PATH = the include path to jni.h
JAVA_INCLUDE_PATH2 = the include path to jni_md.h
JAVA_AWT_INCLUDE_PATH = the include path to jawt.h
```
cmake CheckIncludeFiles CheckIncludeFiles
=================
Provides a macro to check if a list of one or more header files can be included together in `C`.
`CHECK_INCLUDE_FILES`
```
CHECK_INCLUDE_FILES("<includes>" <variable>)
```
Check if the given `<includes>` list may be included together in a `C` source file and store the result in an internal cache entry named `<variable>`. Specify the `<includes>` argument as a [;-list](../manual/cmake-language.7#cmake-language-lists) of header file names.
The following variables may be set before calling this macro to modify the way the check is run:
`CMAKE_REQUIRED_FLAGS` string of compile command line flags
`CMAKE_REQUIRED_DEFINITIONS` list of macros to define (-DFOO=bar)
`CMAKE_REQUIRED_INCLUDES` list of include directories
`CMAKE_REQUIRED_QUIET` execute quietly without messages See modules [`CheckIncludeFile`](checkincludefile#module:CheckIncludeFile "CheckIncludeFile") and [`CheckIncludeFileCXX`](checkincludefilecxx#module:CheckIncludeFileCXX "CheckIncludeFileCXX") to check for a single header file in `C` or `CXX` languages.
cmake FindGIF FindGIF
=======
This finds the GIF library (giflib)
The module defines the following variables:
`GIF_FOUND` True if giflib was found
`GIF_LIBRARIES` Libraries to link to in order to use giflib
`GIF_INCLUDE_DIR` where to find the headers
`GIF_VERSION` 3, 4 or a full version string (eg 5.1.4) for versions >= 4.1.6 The minimum required version of giflib can be specified using the standard syntax, e.g. find\_package(GIF 4)
$GIF\_DIR is an environment variable that would correspond to the ./configure –prefix=$GIF\_DIR
cmake Findosg Findosg
=======
NOTE: It is highly recommended that you use the new FindOpenSceneGraph.cmake introduced in CMake 2.6.3 and not use this Find module directly.
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osg This module defines
OSG\_FOUND - Was the Osg found? OSG\_INCLUDE\_DIR - Where to find the headers OSG\_LIBRARIES - The libraries to link against for the OSG (use this)
OSG\_LIBRARY - The OSG library OSG\_LIBRARY\_DEBUG - The OSG debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake FindHTMLHelp FindHTMLHelp
============
This module looks for Microsoft HTML Help Compiler
It defines:
```
HTML_HELP_COMPILER : full path to the Compiler (hhc.exe)
HTML_HELP_INCLUDE_PATH : include path to the API (htmlhelp.h)
HTML_HELP_LIBRARY : full path to the library (htmlhelp.lib)
```
cmake FindPerlLibs FindPerlLibs
============
Find Perl libraries
This module finds if PERL is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:
```
PERLLIBS_FOUND = True if perl.h & libperl were found
PERL_INCLUDE_PATH = path to where perl.h is found
PERL_LIBRARY = path to libperl
PERL_EXECUTABLE = full path to the perl binary
```
The minimum required version of Perl can be specified using the standard syntax, e.g. find\_package(PerlLibs 6.0)
```
The following variables are also available if needed
(introduced after CMake 2.6.4)
```
```
PERL_SITESEARCH = path to the sitesearch install dir
PERL_SITELIB = path to the sitelib install directory
PERL_VENDORARCH = path to the vendor arch install directory
PERL_VENDORLIB = path to the vendor lib install directory
PERL_ARCHLIB = path to the arch lib install directory
PERL_PRIVLIB = path to the priv lib install directory
PERL_EXTRA_C_FLAGS = Compilation flags used to build perl
```
cmake FindAVIFile FindAVIFile
===========
Locate AVIFILE library and include paths
AVIFILE (<http://avifile.sourceforge.net/)is> a set of libraries for i386 machines to use various AVI codecs. Support is limited beyond Linux. Windows provides native AVI support, and so doesn’t need this library. This module defines
```
AVIFILE_INCLUDE_DIR, where to find avifile.h , etc.
AVIFILE_LIBRARIES, the libraries to link against
AVIFILE_DEFINITIONS, definitions to use when compiling
AVIFILE_FOUND, If false, don't try to use AVIFILE
```
cmake CheckCCompilerFlag CheckCCompilerFlag
==================
Check whether the C compiler supports a given flag.
CHECK\_C\_COMPILER\_FLAG(<flag> <var>)
```
<flag> - the compiler flag
<var> - variable to store the result
Will be created as an internal cache variable.
```
This internally calls the check\_c\_source\_compiles macro and sets CMAKE\_REQUIRED\_DEFINITIONS to <flag>. See help for CheckCSourceCompiles for a listing of variables that can otherwise modify the build. The result only tells that the compiler does not give an error message when it encounters the flag. If the flag has any effect or even a specific one is beyond the scope of this module.
cmake FindOpenMP FindOpenMP
==========
Finds OpenMP support
This module can be used to detect OpenMP support in a compiler. If the compiler supports OpenMP, the flags required to compile with OpenMP support are returned in variables for the different languages. The variables may be empty if the compiler does not need a special flag to support OpenMP.
Variables
---------
This module will set the following variables per language in your project, where `<lang>` is one of C, CXX, or Fortran:
`OpenMP_<lang>_FOUND` Variable indicating if OpenMP support for `<lang>` was detected.
`OpenMP_<lang>_FLAGS` OpenMP compiler flags for `<lang>`, separated by spaces. For linking with OpenMP code written in `<lang>`, the following variables are provided:
`OpenMP_<lang>_LIB_NAMES`
[;-list](../manual/cmake-language.7#cmake-language-lists) of libraries for OpenMP programs for `<lang>`.
`OpenMP_<libname>_LIBRARY` Location of the individual libraries needed for OpenMP support in `<lang>`.
`OpenMP_<lang>_LIBRARIES` A list of libraries needed to link with OpenMP code written in `<lang>`. Additionally, the module provides [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets:
`OpenMP::OpenMP_<lang>` Target for using OpenMP from `<lang>`. Specifically for Fortran, the module sets the following variables:
`OpenMP_Fortran_HAVE_OMPLIB_HEADER` Boolean indicating if OpenMP is accessible through `omp_lib.h`.
`OpenMP_Fortran_HAVE_OMPLIB_MODULE` Boolean indicating if OpenMP is accessible through the `omp_lib` Fortran module. The module will also try to provide the OpenMP version variables:
`OpenMP_<lang>_SPEC_DATE` Date of the OpenMP specification implemented by the `<lang>` compiler.
`OpenMP_<lang>_VERSION_MAJOR` Major version of OpenMP implemented by the `<lang>` compiler.
`OpenMP_<lang>_VERSION_MINOR` Minor version of OpenMP implemented by the `<lang>` compiler.
`OpenMP_<lang>_VERSION` OpenMP version implemented by the `<lang>` compiler. The specification date is formatted as given in the OpenMP standard: `yyyymm` where `yyyy` and `mm` represents the year and month of the OpenMP specification implemented by the `<lang>` compiler.
Backward Compatibility
----------------------
For backward compatibility with older versions of FindOpenMP, these variables are set, but deprecated:
```
OpenMP_FOUND
```
In new projects, please use the `OpenMP_<lang>_XXX` equivalents.
cmake FindJPEG FindJPEG
========
Find JPEG
Find the native JPEG includes and library This module defines
```
JPEG_INCLUDE_DIR, where to find jpeglib.h, etc.
JPEG_LIBRARIES, the libraries needed to use JPEG.
JPEG_FOUND, If false, do not try to use JPEG.
```
also defined, but not for general use are
```
JPEG_LIBRARY, where to find the JPEG library.
```
| programming_docs |
cmake FindLibXml2 FindLibXml2
===========
Try to find the LibXml2 xml processing library
Once done this will define
```
LIBXML2_FOUND - System has LibXml2
LIBXML2_INCLUDE_DIR - The LibXml2 include directory
LIBXML2_LIBRARIES - The libraries needed to use LibXml2
LIBXML2_DEFINITIONS - Compiler switches required for using LibXml2
LIBXML2_XMLLINT_EXECUTABLE - The XML checking tool xmllint coming with LibXml2
LIBXML2_VERSION_STRING - the version of LibXml2 found (since CMake 2.8.8)
```
cmake ProcessorCount ProcessorCount
==============
ProcessorCount(var)
Determine the number of processors/cores and save value in ${var}
Sets the variable named ${var} to the number of physical cores available on the machine if the information can be determined. Otherwise it is set to 0. Currently this functionality is implemented for AIX, cygwin, FreeBSD, HPUX, IRIX, Linux, Mac OS X, QNX, Sun and Windows.
This function is guaranteed to return a positive integer (>=1) if it succeeds. It returns 0 if there’s a problem determining the processor count.
Example use, in a ctest -S dashboard script:
```
include(ProcessorCount)
ProcessorCount(N)
if(NOT N EQUAL 0)
set(CTEST_BUILD_FLAGS -j${N})
set(ctest_test_args ${ctest_test_args} PARALLEL_LEVEL ${N})
endif()
```
This function is intended to offer an approximation of the value of the number of compute cores available on the current machine, such that you may use that value for parallel building and parallel testing. It is meant to help utilize as much of the machine as seems reasonable. Of course, knowledge of what else might be running on the machine simultaneously should be used when deciding whether to request a machine’s full capacity all for yourself.
cmake FindSelfPackers FindSelfPackers
===============
Find upx
This module looks for some executable packers (i.e. software that compress executables or shared libs into on-the-fly self-extracting executables or shared libs. Examples:
```
UPX: http://wildsau.idv.uni-linz.ac.at/mfx/upx.html
```
cmake FindGTest FindGTest
=========
Locate the Google C++ Testing Framework.
Imported targets
----------------
This module defines the following [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets:
`GTest::GTest` The Google Test `gtest` library, if found; adds Thread::Thread automatically
`GTest::Main` The Google Test `gtest_main` library, if found Result variables
----------------
This module will set the following variables in your project:
`GTEST_FOUND` Found the Google Testing framework
`GTEST_INCLUDE_DIRS` the directory containing the Google Test headers The library variables below are set as normal variables. These contain debug/optimized keywords when a debugging library is found.
`GTEST_LIBRARIES` The Google Test `gtest` library; note it also requires linking with an appropriate thread library
`GTEST_MAIN_LIBRARIES` The Google Test `gtest_main` library
`GTEST_BOTH_LIBRARIES` Both `gtest` and `gtest_main`
Cache variables
---------------
The following cache variables may also be set:
`GTEST_ROOT` The root directory of the Google Test installation (may also be set as an environment variable)
`GTEST_MSVC_SEARCH` If compiling with MSVC, this variable can be set to `MT` or `MD` (the default) to enable searching a GTest build tree Example usage
-------------
```
enable_testing()
find_package(GTest REQUIRED)
add_executable(foo foo.cc)
target_link_libraries(foo GTest::GTest GTest::Main)
add_test(AllTestsInFoo foo)
```
Deeper integration with CTest
-----------------------------
See [`GoogleTest`](googletest#module:GoogleTest "GoogleTest") for information on the [`gtest_add_tests()`](googletest#command:gtest_add_tests "gtest_add_tests") command.
cmake FindBoost FindBoost
=========
Find Boost include dirs and libraries
Use this module by invoking find\_package with the form:
```
find_package(Boost
[version] [EXACT] # Minimum or EXACT version e.g. 1.36.0
[REQUIRED] # Fail with error if Boost is not found
[COMPONENTS <libs>...] # Boost libraries by their canonical name
) # e.g. "date_time" for "libboost_date_time"
```
This module finds headers and requested component libraries OR a CMake package configuration file provided by a “Boost CMake” build. For the latter case skip to the “Boost CMake” section below. For the former case results are reported in variables:
```
Boost_FOUND - True if headers and requested libraries were found
Boost_INCLUDE_DIRS - Boost include directories
Boost_LIBRARY_DIRS - Link directories for Boost libraries
Boost_LIBRARIES - Boost component libraries to be linked
Boost_<C>_FOUND - True if component <C> was found (<C> is upper-case)
Boost_<C>_LIBRARY - Libraries to link for component <C> (may include
target_link_libraries debug/optimized keywords)
Boost_VERSION - BOOST_VERSION value from boost/version.hpp
Boost_LIB_VERSION - Version string appended to library filenames
Boost_MAJOR_VERSION - Boost major version number (X in X.y.z)
Boost_MINOR_VERSION - Boost minor version number (Y in x.Y.z)
Boost_SUBMINOR_VERSION - Boost subminor version number (Z in x.y.Z)
Boost_LIB_DIAGNOSTIC_DEFINITIONS (Windows)
- Pass to add_definitions() to have diagnostic
information about Boost's automatic linking
displayed during compilation
```
This module reads hints about search locations from variables:
```
BOOST_ROOT - Preferred installation prefix
(or BOOSTROOT)
BOOST_INCLUDEDIR - Preferred include directory e.g. <prefix>/include
BOOST_LIBRARYDIR - Preferred library directory e.g. <prefix>/lib
Boost_NO_SYSTEM_PATHS - Set to ON to disable searching in locations not
specified by these hint variables. Default is OFF.
Boost_ADDITIONAL_VERSIONS
- List of Boost versions not known to this module
(Boost install locations may contain the version)
```
and saves search results persistently in CMake cache entries:
```
Boost_INCLUDE_DIR - Directory containing Boost headers
Boost_LIBRARY_DIR_RELEASE - Directory containing release Boost libraries
Boost_LIBRARY_DIR_DEBUG - Directory containing debug Boost libraries
Boost_<C>_LIBRARY_DEBUG - Component <C> library debug variant
Boost_<C>_LIBRARY_RELEASE - Component <C> library release variant
```
The following [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets are also defined:
```
Boost::boost - Target for header-only dependencies
(Boost include directory)
Boost::<C> - Target for specific component dependency
(shared or static library); <C> is lower-
case
Boost::diagnostic_definitions - interface target to enable diagnostic
information about Boost's automatic linking
during compilation (adds BOOST_LIB_DIAGNOSTIC)
Boost::disable_autolinking - interface target to disable automatic
linking with MSVC (adds BOOST_ALL_NO_LIB)
Boost::dynamic_linking - interface target to enable dynamic linking
linking with MSVC (adds BOOST_ALL_DYN_LINK)
```
Implicit dependencies such as Boost::filesystem requiring Boost::system will be automatically detected and satisfied, even if system is not specified when using find\_package and if Boost::system is not added to target\_link\_libraries. If using Boost::thread, then Thread::Thread will also be added automatically.
It is important to note that the imported targets behave differently than variables created by this module: multiple calls to find\_package(Boost) in the same directory or sub-directories with different options (e.g. static or shared) will not override the values of the targets created by the first call.
Users may set these hints or results as cache entries. Projects should not read these entries directly but instead use the above result variables. Note that some hint names start in upper-case “BOOST”. One may specify these as environment variables if they are not specified as CMake variables or cache entries.
This module first searches for the Boost header files using the above hint variables (excluding BOOST\_LIBRARYDIR) and saves the result in Boost\_INCLUDE\_DIR. Then it searches for requested component libraries using the above hints (excluding BOOST\_INCLUDEDIR and Boost\_ADDITIONAL\_VERSIONS), “lib” directories near Boost\_INCLUDE\_DIR, and the library name configuration settings below. It saves the library directories in Boost\_LIBRARY\_DIR\_DEBUG and Boost\_LIBRARY\_DIR\_RELEASE and individual library locations in Boost\_<C>\_LIBRARY\_DEBUG and Boost\_<C>\_LIBRARY\_RELEASE. When one changes settings used by previous searches in the same build tree (excluding environment variables) this module discards previous search results affected by the changes and searches again.
Boost libraries come in many variants encoded in their file name. Users or projects may tell this module which variant to find by setting variables:
```
Boost_USE_MULTITHREADED - Set to OFF to use the non-multithreaded
libraries ('mt' tag). Default is ON.
Boost_USE_STATIC_LIBS - Set to ON to force the use of the static
libraries. Default is OFF.
Boost_USE_STATIC_RUNTIME - Set to ON or OFF to specify whether to use
libraries linked statically to the C++ runtime
('s' tag). Default is platform dependent.
Boost_USE_DEBUG_RUNTIME - Set to ON or OFF to specify whether to use
libraries linked to the MS debug C++ runtime
('g' tag). Default is ON.
Boost_USE_DEBUG_PYTHON - Set to ON to use libraries compiled with a
debug Python build ('y' tag). Default is OFF.
Boost_USE_STLPORT - Set to ON to use libraries compiled with
STLPort ('p' tag). Default is OFF.
Boost_USE_STLPORT_DEPRECATED_NATIVE_IOSTREAMS
- Set to ON to use libraries compiled with
STLPort deprecated "native iostreams"
('n' tag). Default is OFF.
Boost_COMPILER - Set to the compiler-specific library suffix
(e.g. "-gcc43"). Default is auto-computed
for the C++ compiler in use. A list may be
used if multiple compatible suffixes should
be tested for, in decreasing order of
preference.
Boost_THREADAPI - Suffix for "thread" component library name,
such as "pthread" or "win32". Names with
and without this suffix will both be tried.
Boost_NAMESPACE - Alternate namespace used to build boost with
e.g. if set to "myboost", will search for
myboost_thread instead of boost_thread.
```
Other variables one may set to control this module are:
```
Boost_DEBUG - Set to ON to enable debug output from FindBoost.
Please enable this before filing any bug report.
Boost_DETAILED_FAILURE_MSG
- Set to ON to add detailed information to the
failure message even when the REQUIRED option
is not given to the find_package call.
Boost_REALPATH - Set to ON to resolve symlinks for discovered
libraries to assist with packaging. For example,
the "system" component library may be resolved to
"/usr/lib/libboost_system.so.1.42.0" instead of
"/usr/lib/libboost_system.so". This does not
affect linking and should not be enabled unless
the user needs this information.
Boost_LIBRARY_DIR - Default value for Boost_LIBRARY_DIR_RELEASE and
Boost_LIBRARY_DIR_DEBUG.
```
On Visual Studio and Borland compilers Boost headers request automatic linking to corresponding libraries. This requires matching libraries to be linked explicitly or available in the link library search path. In this case setting Boost\_USE\_STATIC\_LIBS to OFF may not achieve dynamic linking. Boost automatic linking typically requests static libraries with a few exceptions (such as Boost.Python). Use:
```
add_definitions(${Boost_LIB_DIAGNOSTIC_DEFINITIONS})
```
to ask Boost to report information about automatic linking requests.
Example to find Boost headers only:
```
find_package(Boost 1.36.0)
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(foo foo.cc)
endif()
```
Example to find Boost libraries and use imported targets:
```
find_package(Boost 1.56 REQUIRED COMPONENTS
date_time filesystem iostreams)
add_executable(foo foo.cc)
target_link_libraries(foo Boost::date_time Boost::filesystem
Boost::iostreams)
```
Example to find Boost headers and some *static* libraries:
```
set(Boost_USE_STATIC_LIBS ON) # only find static libs
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost 1.36.0 COMPONENTS date_time filesystem system ...)
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(foo foo.cc)
target_link_libraries(foo ${Boost_LIBRARIES})
endif()
```
Boost CMake
-----------
If Boost was built using the boost-cmake project it provides a package configuration file for use with find\_package’s Config mode. This module looks for the package configuration file called BoostConfig.cmake or boost-config.cmake and stores the result in cache entry “Boost\_DIR”. If found, the package configuration file is loaded and this module returns with no further action. See documentation of the Boost CMake package configuration for details on what it provides.
Set Boost\_NO\_BOOST\_CMAKE to ON to disable the search for boost-cmake.
cmake FindXMLRPC FindXMLRPC
==========
Find xmlrpc
Find the native XMLRPC headers and libraries.
```
XMLRPC_INCLUDE_DIRS - where to find xmlrpc.h, etc.
XMLRPC_LIBRARIES - List of libraries when using xmlrpc.
XMLRPC_FOUND - True if xmlrpc found.
```
XMLRPC modules may be specified as components for this find module. Modules may be listed by running “xmlrpc-c-config”. Modules include:
```
c++ C++ wrapper code
libwww-client libwww-based client
cgi-server CGI-based server
abyss-server ABYSS-based server
```
Typical usage:
```
find_package(XMLRPC REQUIRED libwww-client)
```
cmake FindPike FindPike
========
Find Pike
This module finds if PIKE is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:
```
PIKE_INCLUDE_PATH = path to where program.h is found
PIKE_EXECUTABLE = full path to the pike binary
```
cmake FindosgDB FindosgDB
=========
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgDB This module defines
OSGDB\_FOUND - Was osgDB found? OSGDB\_INCLUDE\_DIR - Where to find the headers OSGDB\_LIBRARIES - The libraries to link against for the osgDB (use this)
OSGDB\_LIBRARY - The osgDB library OSGDB\_LIBRARY\_DEBUG - The osgDB debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake FindLibArchive FindLibArchive
==============
Find libarchive library and headers
The module defines the following variables:
```
LibArchive_FOUND - true if libarchive was found
LibArchive_INCLUDE_DIRS - include search path
LibArchive_LIBRARIES - libraries to link
LibArchive_VERSION - libarchive 3-component version number
```
cmake FindIcotool FindIcotool
===========
Find icotool
This module looks for icotool. This module defines the following values:
```
ICOTOOL_EXECUTABLE: the full path to the icotool tool.
ICOTOOL_FOUND: True if icotool has been found.
ICOTOOL_VERSION_STRING: the version of icotool found.
```
cmake Dart Dart
====
Configure a project for testing with CTest or old Dart Tcl Client
This file is the backwards-compatibility version of the CTest module. It supports using the old Dart 1 Tcl client for driving dashboard submissions as well as testing with CTest. This module should be included in the CMakeLists.txt file at the top of a project. Typical usage:
```
include(Dart)
if(BUILD_TESTING)
# ... testing related CMake code ...
endif()
```
The BUILD\_TESTING option is created by the Dart module to determine whether testing support should be enabled. The default is ON.
cmake FindMatlab FindMatlab
==========
Finds Matlab installations and provides Matlab tools and libraries to cmake.
This package first intention is to find the libraries associated with Matlab in order to be able to build Matlab extensions (mex files). It can also be used:
* run specific commands in Matlab
* declare Matlab unit test
* retrieve various information from Matlab (mex extensions, versions and release queries, …)
The module supports the following components:
* `MX_LIBRARY`, `ENG_LIBRARY` and `MAT_LIBRARY`: respectively the MX, ENG and MAT libraries of Matlab
* `MAIN_PROGRAM` the Matlab binary program.
* `MEX_COMPILER` the MEX compiler.
* `SIMULINK` the Simulink environment.
Note
The version given to the [`find_package()`](../command/find_package#command:find_package "find_package") directive is the Matlab **version**, which should not be confused with the Matlab *release* name (eg. `R2014`). The [`matlab_get_version_from_release_name()`](#command:matlab_get_version_from_release_name "matlab_get_version_from_release_name") and [`matlab_get_release_name_from_version()`](#command:matlab_get_release_name_from_version "matlab_get_release_name_from_version") allow a mapping from the release name to the version.
The variable [`Matlab_ROOT_DIR`](#variable:Matlab_ROOT_DIR "Matlab_ROOT_DIR") may be specified in order to give the path of the desired Matlab version. Otherwise, the behaviour is platform specific:
* Windows: The installed versions of Matlab are retrieved from the Windows registry
* OS X: The installed versions of Matlab are given by the MATLAB paths in `/Application`. If no such application is found, it falls back to the one that might be accessible from the PATH.
* Unix: The desired Matlab should be accessible from the PATH.
Additional information is provided when [`MATLAB_FIND_DEBUG`](#variable:MATLAB_FIND_DEBUG "MATLAB_FIND_DEBUG") is set. When a Matlab binary is found automatically and the `MATLAB_VERSION` is not given, the version is queried from Matlab directly. On Windows, it can make a window running Matlab appear.
The mapping of the release names and the version of Matlab is performed by defining pairs (name, version). The variable [`MATLAB_ADDITIONAL_VERSIONS`](#variable:MATLAB_ADDITIONAL_VERSIONS "MATLAB_ADDITIONAL_VERSIONS") may be provided before the call to the [`find_package()`](../command/find_package#command:find_package "find_package") in order to handle additional versions.
A Matlab scripts can be added to the set of tests using the [`matlab_add_unit_test()`](#command:matlab_add_unit_test "matlab_add_unit_test"). By default, the Matlab unit test framework will be used (>= 2013a) to run this script, but regular `.m` files returning an exit code can be used as well (0 indicating a success).
Module Input Variables
----------------------
Users or projects may set the following variables to configure the module behaviour:
[`Matlab_ROOT_DIR`](#variable:Matlab_ROOT_DIR "Matlab_ROOT_DIR")
the root of the Matlab installation.
[`MATLAB_FIND_DEBUG`](#variable:MATLAB_FIND_DEBUG "MATLAB_FIND_DEBUG")
outputs debug information
[`MATLAB_ADDITIONAL_VERSIONS`](#variable:MATLAB_ADDITIONAL_VERSIONS "MATLAB_ADDITIONAL_VERSIONS")
additional versions of Matlab for the automatic retrieval of the installed versions. Variables defined by the module
-------------------------------
### Result variables
`Matlab_FOUND`
`TRUE` if the Matlab installation is found, `FALSE` otherwise. All variable below are defined if Matlab is found.
`Matlab_ROOT_DIR` the final root of the Matlab installation determined by the FindMatlab module.
`Matlab_MAIN_PROGRAM` the Matlab binary program. Available only if the component `MAIN_PROGRAM` is given in the [`find_package()`](../command/find_package#command:find_package "find_package") directive.
`Matlab_INCLUDE_DIRS` the path of the Matlab libraries headers
`Matlab_MEX_LIBRARY` library for mex, always available.
`Matlab_MX_LIBRARY` mx library of Matlab (arrays). Available only if the component `MX_LIBRARY` has been requested.
`Matlab_ENG_LIBRARY` Matlab engine library. Available only if the component `ENG_LIBRARY` is requested.
`Matlab_MAT_LIBRARY` Matlab matrix library. Available only if the component `MAT_LIBRARY` is requested.
`Matlab_LIBRARIES` the whole set of libraries of Matlab
`Matlab_MEX_COMPILER` the mex compiler of Matlab. Currently not used. Available only if the component `MEX_COMPILER` is asked ### Cached variables
`Matlab_MEX_EXTENSION` the extension of the mex files for the current platform (given by Matlab).
`Matlab_ROOT_DIR` the location of the root of the Matlab installation found. If this value is changed by the user, the result variables are recomputed. Provided macros
---------------
[`matlab_get_version_from_release_name()`](#command:matlab_get_version_from_release_name "matlab_get_version_from_release_name")
returns the version from the release name
[`matlab_get_release_name_from_version()`](#command:matlab_get_release_name_from_version "matlab_get_release_name_from_version")
returns the release name from the Matlab version Provided functions
------------------
[`matlab_add_mex()`](#command:matlab_add_mex "matlab_add_mex")
adds a target compiling a MEX file.
[`matlab_add_unit_test()`](#command:matlab_add_unit_test "matlab_add_unit_test")
adds a Matlab unit test file as a test to the project.
[`matlab_extract_all_installed_versions_from_registry()`](#command:matlab_extract_all_installed_versions_from_registry "matlab_extract_all_installed_versions_from_registry")
parses the registry for all Matlab versions. Available on Windows only. The part of the registry parsed is dependent on the host processor
[`matlab_get_all_valid_matlab_roots_from_registry()`](#command:matlab_get_all_valid_matlab_roots_from_registry "matlab_get_all_valid_matlab_roots_from_registry")
returns all the possible Matlab paths, according to a previously given list. Only the existing/accessible paths are kept. This is mainly useful for the searching all possible Matlab installation.
[`matlab_get_mex_suffix()`](#command:matlab_get_mex_suffix "matlab_get_mex_suffix")
returns the suffix to be used for the mex files (platform/architecture dependent)
[`matlab_get_version_from_matlab_run()`](#command:matlab_get_version_from_matlab_run "matlab_get_version_from_matlab_run")
returns the version of Matlab, given the full directory of the Matlab program. Known issues
------------
**Symbol clash in a MEX target**
By default, every symbols inside a MEX file defined with the command [`matlab_add_mex()`](#command:matlab_add_mex "matlab_add_mex") have hidden visibility, except for the entry point. This is the default behaviour of the MEX compiler, which lowers the risk of symbol collision between the libraries shipped with Matlab, and the libraries to which the MEX file is linking to. This is also the default on Windows platforms.
However, this is not sufficient in certain case, where for instance your MEX file is linking against libraries that are already loaded by Matlab, even if those libraries have different SONAMES. A possible solution is to hide the symbols of the libraries to which the MEX target is linking to. This can be achieved in GNU GCC compilers with the linker option `-Wl,--exclude-libs,ALL`.
**Tests using GPU resources** in case your MEX file is using the GPU and in order to be able to run unit tests on this MEX file, the GPU resources should be properly released by Matlab. A possible solution is to make Matlab aware of the use of the GPU resources in the session, which can be performed by a command such as `D = gpuDevice()` at the beginning of the test script (or via a fixture). Reference
---------
`Matlab_ROOT_DIR`
The root folder of the Matlab installation. If set before the call to [`find_package()`](../command/find_package#command:find_package "find_package"), the module will look for the components in that path. If not set, then an automatic search of Matlab will be performed. If set, it should point to a valid version of Matlab.
`MATLAB_FIND_DEBUG`
If set, the lookup of Matlab and the intermediate configuration steps are outputted to the console.
`MATLAB_ADDITIONAL_VERSIONS`
If set, specifies additional versions of Matlab that may be looked for. The variable should be a list of strings, organised by pairs of release name and versions, such as follows:
```
set(MATLAB_ADDITIONAL_VERSIONS
"release_name1=corresponding_version1"
"release_name2=corresponding_version2"
...
)
```
Example:
```
set(MATLAB_ADDITIONAL_VERSIONS
"R2013b=8.2"
"R2013a=8.1"
"R2012b=8.0")
```
The order of entries in this list matters when several versions of Matlab are installed. The priority is set according to the ordering in this list.
`matlab_get_version_from_release_name`
Returns the version of Matlab (17.58) from a release name (R2017k)
`matlab_get_release_name_from_version`
Returns the release name (R2017k) from the version of Matlab (17.58)
`matlab_extract_all_installed_versions_from_registry`
This function parses the registry and founds the Matlab versions that are installed. The found versions are returned in `matlab_versions`. Set `win64` to `TRUE` if the 64 bit version of Matlab should be looked for The returned list contains all versions under `HKLM\\SOFTWARE\\Mathworks\\MATLAB` or an empty list in case an error occurred (or nothing found).
Note
Only the versions are provided. No check is made over the existence of the installation referenced in the registry,
`matlab_get_all_valid_matlab_roots_from_registry`
Populates the Matlab root with valid versions of Matlab. The returned matlab\_roots is organized in pairs `(version_number,matlab_root_path)`.
```
matlab_get_all_valid_matlab_roots_from_registry(
matlab_versions
matlab_roots)
```
`matlab_versions` the versions of each of the Matlab installations
`matlab_roots` the location of each of the Matlab installations
`matlab_get_mex_suffix`
Returns the extension of the mex files (the suffixes). This function should not be called before the appropriate Matlab root has been found.
```
matlab_get_mex_suffix(
matlab_root
mex_suffix)
```
`matlab_root` the root of the Matlab installation
`mex_suffix` the variable name in which the suffix will be returned.
`matlab_get_version_from_matlab_run`
This function runs Matlab program specified on arguments and extracts its version.
```
matlab_get_version_from_matlab_run(
matlab_binary_path
matlab_list_versions)
```
`matlab_binary_path` the location of the `matlab` binary executable
`matlab_list_versions` the version extracted from Matlab
`matlab_add_unit_test`
Adds a Matlab unit test to the test set of cmake/ctest. This command requires the component `MAIN_PROGRAM`. The unit test uses the Matlab unittest framework (default, available starting Matlab 2013b+) except if the option `NO_UNITTEST_FRAMEWORK` is given.
The function expects one Matlab test script file to be given. In the case `NO_UNITTEST_FRAMEWORK` is given, the unittest script file should contain the script to be run, plus an exit command with the exit value. This exit value will be passed to the ctest framework (0 success, non 0 failure). Additional arguments accepted by [`add_test()`](../command/add_test#command:add_test "add_test") can be passed through `TEST_ARGS` (eg. `CONFIGURATION <config> ...`).
```
matlab_add_unit_test(
NAME <name>
UNITTEST_FILE matlab_file_containing_unittest.m
[CUSTOM_MATLAB_COMMAND matlab_command_to_run_as_test]
[UNITTEST_PRECOMMAND matlab_command_to_run]
[TIMEOUT timeout]
[ADDITIONAL_PATH path1 [path2 ...]]
[MATLAB_ADDITIONAL_STARTUP_OPTIONS option1 [option2 ...]]
[TEST_ARGS arg1 [arg2 ...]]
[NO_UNITTEST_FRAMEWORK]
)
```
The function arguments are:
`NAME` name of the unittest in ctest.
`UNITTEST_FILE` the matlab unittest file. Its path will be automatically added to the Matlab path.
`CUSTOM_MATLAB_COMMAND` Matlab script command to run as the test. If this is not set, then the following is run: `runtests('matlab_file_name'), exit(max([ans(1,:).Failed]))` where `matlab_file_name` is the `UNITTEST_FILE` without the extension.
`UNITTEST_PRECOMMAND` Matlab script command to be ran before the file containing the test (eg. GPU device initialisation based on CMake variables).
`TIMEOUT` the test timeout in seconds. Defaults to 180 seconds as the Matlab unit test may hang.
`ADDITIONAL_PATH` a list of paths to add to the Matlab path prior to running the unit test.
`MATLAB_ADDITIONAL_STARTUP_OPTIONS` a list of additional option in order to run Matlab from the command line. `-nosplash -nodesktop -nodisplay` are always added.
`TEST_ARGS` Additional options provided to the add\_test command. These options are added to the default options (eg. “CONFIGURATIONS Release”)
`NO_UNITTEST_FRAMEWORK` when set, indicates that the test should not use the unittest framework of Matlab (available for versions >= R2013a).
`WORKING_DIRECTORY` This will be the working directory for the test. If specified it will also be the output directory used for the log file of the test run. If not specifed the temporary directory `${CMAKE_BINARY_DIR}/Matlab` will be used as the working directory and the log location.
`matlab_add_mex`
Adds a Matlab MEX target. This commands compiles the given sources with the current tool-chain in order to produce a MEX file. The final name of the produced output may be specified, as well as additional link libraries, and a documentation entry for the MEX file. Remaining arguments of the call are passed to the [`add_library()`](../command/add_library#command:add_library "add_library") or [`add_executable()`](../command/add_executable#command:add_executable "add_executable") command.
```
matlab_add_mex(
NAME <name>
[EXECUTABLE | MODULE | SHARED]
SRC src1 [src2 ...]
[OUTPUT_NAME output_name]
[DOCUMENTATION file.txt]
[LINK_TO target1 target2 ...]
[...]
)
```
`NAME` name of the target.
`SRC` list of source files.
`LINK_TO` a list of additional link dependencies. The target links to `libmex` by default. If `Matlab_MX_LIBRARY` is defined, it also links to `libmx`.
`OUTPUT_NAME` if given, overrides the default name. The default name is the name of the target without any prefix and with `Matlab_MEX_EXTENSION` suffix.
`DOCUMENTATION` if given, the file `file.txt` will be considered as being the documentation file for the MEX file. This file is copied into the same folder without any processing, with the same name as the final mex file, and with extension `.m`. In that case, typing `help <name>` in Matlab prints the documentation contained in this file.
`MODULE or SHARED may be given to specify the type of library to be` created. `EXECUTABLE` may be given to create an executable instead of a library. If no type is given explicitly, the type is `SHARED`. The documentation file is not processed and should be in the following format:
```
% This is the documentation
function ret = mex_target_output_name(input1)
```
| programming_docs |
cmake FindGLEW FindGLEW
========
Find the OpenGL Extension Wrangler Library (GLEW)
IMPORTED Targets
----------------
This module defines the [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target `GLEW::GLEW`, if GLEW has been found.
Result Variables
----------------
This module defines the following variables:
```
GLEW_INCLUDE_DIRS - include directories for GLEW
GLEW_LIBRARIES - libraries to link against GLEW
GLEW_FOUND - true if GLEW has been found and can be used
```
cmake FindSDL_mixer FindSDL\_mixer
==============
Locate SDL\_mixer library
This module defines:
```
SDL_MIXER_LIBRARIES, the name of the library to link against
SDL_MIXER_INCLUDE_DIRS, where to find the headers
SDL_MIXER_FOUND, if false, do not try to link against
SDL_MIXER_VERSION_STRING - human-readable string containing the
version of SDL_mixer
```
For backward compatibility the following variables are also set:
```
SDLMIXER_LIBRARY (same value as SDL_MIXER_LIBRARIES)
SDLMIXER_INCLUDE_DIR (same value as SDL_MIXER_INCLUDE_DIRS)
SDLMIXER_FOUND (same value as SDL_MIXER_FOUND)
```
$SDLDIR is an environment variable that would correspond to the ./configure –prefix=$SDLDIR used in building SDL.
Created by Eric Wing. This was influenced by the FindSDL.cmake module, but with modifications to recognize OS X frameworks and additional Unix paths (FreeBSD, etc).
cmake FindosgQt FindosgQt
=========
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgQt This module defines
OSGQT\_FOUND - Was osgQt found? OSGQT\_INCLUDE\_DIR - Where to find the headers OSGQT\_LIBRARIES - The libraries to link for osgQt (use this)
OSGQT\_LIBRARY - The osgQt library OSGQT\_LIBRARY\_DEBUG - The osgQt debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing. Modified to work with osgQt by Robert Osfield, January 2012.
cmake FindHg FindHg
======
Extract information from a mercurial working copy.
The module defines the following variables:
```
HG_EXECUTABLE - path to mercurial command line client (hg)
HG_FOUND - true if the command line client was found
HG_VERSION_STRING - the version of mercurial found
```
If the command line client executable is found the following macro is defined:
```
HG_WC_INFO(<dir> <var-prefix>)
```
Hg\_WC\_INFO extracts information of a mercurial working copy at a given location. This macro defines the following variables:
```
<var-prefix>_WC_CHANGESET - current changeset
<var-prefix>_WC_REVISION - current revision
```
Example usage:
```
find_package(Hg)
if(HG_FOUND)
message("hg found: ${HG_EXECUTABLE}")
HG_WC_INFO(${PROJECT_SOURCE_DIR} Project)
message("Current revision is ${Project_WC_REVISION}")
message("Current changeset is ${Project_WC_CHANGESET}")
endif()
```
cmake FindJasper FindJasper
==========
Try to find the Jasper JPEG2000 library
Once done this will define
```
JASPER_FOUND - system has Jasper
JASPER_INCLUDE_DIR - the Jasper include directory
JASPER_LIBRARIES - the libraries needed to use Jasper
JASPER_VERSION_STRING - the version of Jasper found (since CMake 2.8.8)
```
cmake FindFreetype FindFreetype
============
Locate FreeType library
This module defines
```
FREETYPE_LIBRARIES, the library to link against
FREETYPE_FOUND, if false, do not try to link to FREETYPE
FREETYPE_INCLUDE_DIRS, where to find headers.
FREETYPE_VERSION_STRING, the version of freetype found (since CMake 2.8.8)
This is the concatenation of the paths:
FREETYPE_INCLUDE_DIR_ft2build
FREETYPE_INCLUDE_DIR_freetype2
```
$FREETYPE\_DIR is an environment variable that would correspond to the ./configure –prefix=$FREETYPE\_DIR used in building FREETYPE.
cmake CPackIFWConfigureFile CPackIFWConfigureFile
=====================
The module defines [`configure_file()`](../command/configure_file#command:configure_file "configure_file") similar command to configure file templates prepared in QtIFW/SDK/Creator style.
Commands
--------
The module defines the following commands:
`cpack_ifw_configure_file`
Copy a file to another location and modify its contents.
```
cpack_ifw_configure_file(<input> <output>)
```
Copies an `<input>` file to an `<output>` file and substitutes variable values referenced as `%{VAR}` or `%VAR%` in the input file content. Each variable reference will be replaced with the current value of the variable, or the empty string if the variable is not defined.
cmake FindGit FindGit
=======
The module defines the following variables:
`GIT_EXECUTABLE` Path to Git command-line client.
`Git_FOUND, GIT_FOUND` True if the Git command-line client was found.
`GIT_VERSION_STRING` The version of Git found. Example usage:
```
find_package(Git)
if(Git_FOUND)
message("Git found: ${GIT_EXECUTABLE}")
endif()
```
cmake FindLua50 FindLua50
=========
Locate Lua library This module defines
```
LUA50_FOUND, if false, do not try to link to Lua
LUA_LIBRARIES, both lua and lualib
LUA_INCLUDE_DIR, where to find lua.h and lualib.h (and probably lauxlib.h)
```
Note that the expected include convention is
```
#include "lua.h"
```
and not
```
#include <lua/lua.h>
```
This is because, the lua location is not standardized and may exist in locations other than lua/
cmake FindPackageHandleStandardArgs FindPackageHandleStandardArgs
=============================
This module provides a function intended to be used in [Find Modules](../manual/cmake-developer.7#find-modules) implementing [`find_package(<PackageName>)`](../command/find_package#command:find_package "find_package") calls. It handles the `REQUIRED`, `QUIET` and version-related arguments of `find_package`. It also sets the `<PackageName>_FOUND` variable. The package is considered found if all variables listed contain valid results, e.g. valid filepaths.
`find_package_handle_standard_args`
There are two signatures:
```
find_package_handle_standard_args(<PackageName>
(DEFAULT_MSG|<custom-failure-message>)
<required-var>...
)
find_package_handle_standard_args(<PackageName>
[FOUND_VAR <result-var>]
[REQUIRED_VARS <required-var>...]
[VERSION_VAR <version-var>]
[HANDLE_COMPONENTS]
[CONFIG_MODE]
[FAIL_MESSAGE <custom-failure-message>]
)
```
The `<PackageName>_FOUND` variable will be set to `TRUE` if all the variables `<required-var>...` are valid and any optional constraints are satisfied, and `FALSE` otherwise. A success or failure message may be displayed based on the results and on whether the `REQUIRED` and/or `QUIET` option was given to the [`find_package()`](../command/find_package#command:find_package "find_package") call.
The options are:
`(DEFAULT_MSG|<custom-failure-message>)` In the simple signature this specifies the failure message. Use `DEFAULT_MSG` to ask for a default message to be computed (recommended). Not valid in the full signature.
`FOUND_VAR <result-var>` Obsolete. Specifies either `<PackageName>_FOUND` or `<PACKAGENAME>_FOUND` as the result variable. This exists only for compatibility with older versions of CMake and is now ignored. Result variables of both names are always set for compatibility.
`REQUIRED_VARS <required-var>...` Specify the variables which are required for this package. These may be named in the generated failure message asking the user to set the missing variable values. Therefore these should typically be cache entries such as `FOO_LIBRARY` and not output variables like `FOO_LIBRARIES`.
`VERSION_VAR <version-var>` Specify the name of a variable that holds the version of the package that has been found. This version will be checked against the (potentially) specified required version given to the [`find_package()`](../command/find_package#command:find_package "find_package") call, including its `EXACT` option. The default messages include information about the required version and the version which has been actually found, both if the version is ok or not.
`HANDLE_COMPONENTS` Enable handling of package components. In this case, the command will report which components have been found and which are missing, and the `<PackageName>_FOUND` variable will be set to `FALSE` if any of the required components (i.e. not the ones listed after the `OPTIONAL_COMPONENTS` option of [`find_package()`](../command/find_package#command:find_package "find_package")) are missing.
`CONFIG_MODE` Specify that the calling find module is a wrapper around a call to `find_package(<PackageName> NO_MODULE)`. This implies a `VERSION_VAR` value of `<PackageName>_VERSION`. The command will automatically check whether the package configuration file was found.
`FAIL_MESSAGE <custom-failure-message>` Specify a custom failure message instead of using the default generated message. Not recommended.
Example for the simple signature:
```
find_package_handle_standard_args(LibXml2 DEFAULT_MSG
LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR)
```
The `LibXml2` package is considered to be found if both `LIBXML2_LIBRARY` and `LIBXML2_INCLUDE_DIR` are valid. Then also `LibXml2_FOUND` is set to `TRUE`. If it is not found and `REQUIRED` was used, it fails with a [`message(FATAL_ERROR)`](../command/message#command:message "message"), independent whether `QUIET` was used or not. If it is found, success will be reported, including the content of the first `<required-var>`. On repeated CMake runs, the same message will not be printed again.
Example for the full signature:
```
find_package_handle_standard_args(LibArchive
REQUIRED_VARS LibArchive_LIBRARY LibArchive_INCLUDE_DIR
VERSION_VAR LibArchive_VERSION)
```
In this case, the `LibArchive` package is considered to be found if both `LibArchive_LIBRARY` and `LibArchive_INCLUDE_DIR` are valid. Also the version of `LibArchive` will be checked by using the version contained in `LibArchive_VERSION`. Since no `FAIL_MESSAGE` is given, the default messages will be printed.
Another example for the full signature:
```
find_package(Automoc4 QUIET NO_MODULE HINTS /opt/automoc4)
find_package_handle_standard_args(Automoc4 CONFIG_MODE)
```
In this case, a `FindAutmoc4.cmake` module wraps a call to `find_package(Automoc4 NO_MODULE)` and adds an additional search directory for `automoc4`. Then the call to `find_package_handle_standard_args` produces a proper success/failure message.
cmake CPackRPM CPackRPM
========
The built in (binary) CPack RPM generator (Unix only)
Variables specific to CPack RPM generator
-----------------------------------------
CPackRPM may be used to create RPM packages using [`CPack`](cpack#module:CPack "CPack"). CPackRPM is a [`CPack`](cpack#module:CPack "CPack") generator thus it uses the `CPACK_XXX` variables used by [`CPack`](cpack#module:CPack "CPack").
CPackRPM has specific features which are controlled by the specifics `CPACK_RPM_XXX` variables.
`CPACK_RPM_<COMPONENT>_XXXX` variables may be used in order to have **component** specific values. Note however that `<COMPONENT>` refers to the **grouping name** written in upper case. It may be either a component name or a component GROUP name. Usually those variables correspond to RPM spec file entities. One may find information about spec files here <http://www.rpm.org/wiki/Docs>
Note
`<COMPONENT>` part of variables is preferred to be in upper case (for e.g. if component is named `foo` then use `CPACK_RPM_FOO_XXXX` variable name format) as is with other `CPACK_<COMPONENT>_XXXX` variables. For the purposes of back compatibility (CMake/CPack version 3.5 and lower) support for same cased component (e.g. `fOo` would be used as `CPACK_RPM_fOo_XXXX`) is still supported for variables defined in older versions of CMake/CPack but is not guaranteed for variables that will be added in the future. For the sake of back compatibility same cased component variables also override upper cased versions where both are present.
Here are some CPackRPM wiki resources that are here for historic reasons and are no longer maintained but may still prove useful:
* <https://cmake.org/Wiki/CMake:CPackConfiguration>
* <https://cmake.org/Wiki/CMake:CPackPackageGenerators#RPM_.28Unix_Only.29>
List of CPackRPM specific variables:
`CPACK_RPM_COMPONENT_INSTALL`
Enable component packaging for CPackRPM
* Mandatory : NO
* Default : OFF
If enabled (ON) multiple packages are generated. By default a single package containing files of all components is generated.
`CPACK_RPM_PACKAGE_SUMMARY`
`CPACK_RPM_<component>_PACKAGE_SUMMARY`
The RPM package summary.
* Mandatory : YES
* Default : [`CPACK_PACKAGE_DESCRIPTION_SUMMARY`](cpack#variable:CPACK_PACKAGE_DESCRIPTION_SUMMARY "CPACK_PACKAGE_DESCRIPTION_SUMMARY")
`CPACK_RPM_PACKAGE_NAME`
`CPACK_RPM_<component>_PACKAGE_NAME`
The RPM package name.
* Mandatory : YES
* Default : [`CPACK_PACKAGE_NAME`](cpack#variable:CPACK_PACKAGE_NAME "CPACK_PACKAGE_NAME")
`CPACK_RPM_FILE_NAME`
`CPACK_RPM_<component>_FILE_NAME`
Package file name.
* Mandatory : YES
* `Default : <CPACK_PACKAGE_FILE_NAME>[-<component>].rpm with spaces`
replaced by ‘-‘
This may be set to `RPM-DEFAULT` to allow rpmbuild tool to generate package file name by itself. Alternatively provided package file name must end with `.rpm` suffix.
Note
By using user provided spec file, rpm macro extensions such as for generating debuginfo packages or by simply using multiple components more than one rpm file may be generated, either from a single spec file or from multiple spec files (each component execution produces it’s own spec file). In such cases duplicate file names may occur as a result of this variable setting or spec file content structure. Duplicate files get overwritten and it is up to the packager to set the variables in a manner that will prevent such errors.
`CPACK_RPM_MAIN_COMPONENT`
Main component that is packaged without component suffix.
* Mandatory : NO
* Default : -
This variable can be set to any component or group name so that component or group rpm package is generated without component suffix in filename and package name.
`CPACK_RPM_PACKAGE_VERSION`
The RPM package version.
* Mandatory : YES
* Default : [`CPACK_PACKAGE_VERSION`](cpack#variable:CPACK_PACKAGE_VERSION "CPACK_PACKAGE_VERSION")
`CPACK_RPM_PACKAGE_ARCHITECTURE`
`CPACK_RPM_<component>_PACKAGE_ARCHITECTURE`
The RPM package architecture.
* Mandatory : YES
* Default : Native architecture output by `uname -m`
This may be set to `noarch` if you know you are building a noarch package.
`CPACK_RPM_PACKAGE_RELEASE`
The RPM package release.
* Mandatory : YES
* Default : 1
This is the numbering of the RPM package itself, i.e. the version of the packaging and not the version of the content (see [`CPACK_RPM_PACKAGE_VERSION`](#variable:CPACK_RPM_PACKAGE_VERSION "CPACK_RPM_PACKAGE_VERSION")). One may change the default value if the previous packaging was buggy and/or you want to put here a fancy Linux distro specific numbering.
Note
This is the string that goes into the RPM `Release:` field. Some distros (e.g. Fedora, CentOS) require `1%{?dist}` format and not just a number. `%{?dist}` part can be added by setting [`CPACK_RPM_PACKAGE_RELEASE_DIST`](#variable:CPACK_RPM_PACKAGE_RELEASE_DIST "CPACK_RPM_PACKAGE_RELEASE_DIST").
`CPACK_RPM_PACKAGE_RELEASE_DIST`
The dist tag that is added RPM `Release:` field.
* Mandatory : NO
* Default : OFF
This is the reported `%{dist}` tag from the current distribution or empty `%{dist}` if RPM macro is not set. If this variable is set then RPM `Release:` field value is set to `${CPACK_RPM_PACKAGE_RELEASE}%{?dist}`.
`CPACK_RPM_PACKAGE_LICENSE`
The RPM package license policy.
* Mandatory : YES
* Default : “unknown”
`CPACK_RPM_PACKAGE_GROUP`
`CPACK_RPM_<component>_PACKAGE_GROUP`
The RPM package group.
* Mandatory : YES
* Default : “unknown”
`CPACK_RPM_PACKAGE_VENDOR`
The RPM package vendor.
* Mandatory : YES
* Default : CPACK\_PACKAGE\_VENDOR if set or “unknown”
`CPACK_RPM_PACKAGE_URL`
`CPACK_RPM_<component>_PACKAGE_URL`
The projects URL.
* Mandatory : NO
* Default : -
`CPACK_RPM_PACKAGE_DESCRIPTION`
`CPACK_RPM_<component>_PACKAGE_DESCRIPTION`
RPM package description.
* Mandatory : YES
* Default : [`CPACK_COMPONENT_<compName>_DESCRIPTION`](# "CPACK_COMPONENT_<compName>_DESCRIPTION") (component based installers only) if set, [`CPACK_PACKAGE_DESCRIPTION_FILE`](cpack#variable:CPACK_PACKAGE_DESCRIPTION_FILE "CPACK_PACKAGE_DESCRIPTION_FILE") if set or “no package description available”
`CPACK_RPM_COMPRESSION_TYPE`
RPM compression type.
* Mandatory : NO
* Default : -
May be used to override RPM compression type to be used to build the RPM. For example some Linux distribution now default to lzma or xz compression whereas older cannot use such RPM. Using this one can enforce compression type to be used.
Possible values are:
* lzma
* xz
* bzip2
* gzip
`CPACK_RPM_PACKAGE_AUTOREQ`
`CPACK_RPM_<component>_PACKAGE_AUTOREQ`
RPM spec autoreq field.
* Mandatory : NO
* Default : -
May be used to enable (1, yes) or disable (0, no) automatic shared libraries dependency detection. Dependencies are added to requires list.
Note
By default automatic dependency detection is enabled by rpm generator.
`CPACK_RPM_PACKAGE_AUTOPROV`
`CPACK_RPM_<component>_PACKAGE_AUTOPROV`
RPM spec autoprov field.
* Mandatory : NO
* Default : -
May be used to enable (1, yes) or disable (0, no) automatic listing of shared libraries that are provided by the package. Shared libraries are added to provides list.
Note
By default automatic provides detection is enabled by rpm generator.
`CPACK_RPM_PACKAGE_AUTOREQPROV`
`CPACK_RPM_<component>_PACKAGE_AUTOREQPROV`
RPM spec autoreqprov field.
* Mandatory : NO
* Default : -
Variable enables/disables autoreq and autoprov at the same time. See [`CPACK_RPM_PACKAGE_AUTOREQ`](#variable:CPACK_RPM_PACKAGE_AUTOREQ "CPACK_RPM_PACKAGE_AUTOREQ") and [`CPACK_RPM_PACKAGE_AUTOPROV`](#variable:CPACK_RPM_PACKAGE_AUTOPROV "CPACK_RPM_PACKAGE_AUTOPROV") for more details.
Note
By default automatic detection feature is enabled by rpm.
`CPACK_RPM_PACKAGE_REQUIRES`
`CPACK_RPM_<component>_PACKAGE_REQUIRES`
RPM spec requires field.
* Mandatory : NO
* Default : -
May be used to set RPM dependencies (requires). Note that you must enclose the complete requires string between quotes, for example:
```
set(CPACK_RPM_PACKAGE_REQUIRES "python >= 2.5.0, cmake >= 2.8")
```
The required package list of an RPM file could be printed with:
```
rpm -qp --requires file.rpm
```
`CPACK_RPM_PACKAGE_CONFLICTS`
`CPACK_RPM_<component>_PACKAGE_CONFLICTS`
RPM spec conflicts field.
* Mandatory : NO
* Default : -
May be used to set negative RPM dependencies (conflicts). Note that you must enclose the complete requires string between quotes, for example:
```
set(CPACK_RPM_PACKAGE_CONFLICTS "libxml2")
```
The conflicting package list of an RPM file could be printed with:
```
rpm -qp --conflicts file.rpm
```
`CPACK_RPM_PACKAGE_REQUIRES_PRE`
`CPACK_RPM_<component>_PACKAGE_REQUIRES_PRE`
RPM spec requires(pre) field.
* Mandatory : NO
* Default : -
May be used to set RPM preinstall dependencies (requires(pre)). Note that you must enclose the complete requires string between quotes, for example:
```
set(CPACK_RPM_PACKAGE_REQUIRES_PRE "shadow-utils, initscripts")
```
`CPACK_RPM_PACKAGE_REQUIRES_POST`
`CPACK_RPM_<component>_PACKAGE_REQUIRES_POST`
RPM spec requires(post) field.
* Mandatory : NO
* Default : -
May be used to set RPM postinstall dependencies (requires(post)). Note that you must enclose the complete requires string between quotes, for example:
```
set(CPACK_RPM_PACKAGE_REQUIRES_POST "shadow-utils, initscripts")
```
`CPACK_RPM_PACKAGE_REQUIRES_POSTUN`
`CPACK_RPM_<component>_PACKAGE_REQUIRES_POSTUN`
RPM spec requires(postun) field.
* Mandatory : NO
* Default : -
May be used to set RPM postuninstall dependencies (requires(postun)). Note that you must enclose the complete requires string between quotes, for example:
```
set(CPACK_RPM_PACKAGE_REQUIRES_POSTUN "shadow-utils, initscripts")
```
`CPACK_RPM_PACKAGE_REQUIRES_PREUN`
`CPACK_RPM_<component>_PACKAGE_REQUIRES_PREUN`
RPM spec requires(preun) field.
* Mandatory : NO
* Default : -
May be used to set RPM preuninstall dependencies (requires(preun)). Note that you must enclose the complete requires string between quotes, for example:
```
set(CPACK_RPM_PACKAGE_REQUIRES_PREUN "shadow-utils, initscripts")
```
`CPACK_RPM_PACKAGE_SUGGESTS`
`CPACK_RPM_<component>_PACKAGE_SUGGESTS`
RPM spec suggest field.
* Mandatory : NO
* Default : -
May be used to set weak RPM dependencies (suggests). Note that you must enclose the complete requires string between quotes.
`CPACK_RPM_PACKAGE_PROVIDES`
`CPACK_RPM_<component>_PACKAGE_PROVIDES`
RPM spec provides field.
* Mandatory : NO
* Default : -
May be used to set RPM dependencies (provides). The provided package list of an RPM file could be printed with:
```
rpm -qp --provides file.rpm
```
`CPACK_RPM_PACKAGE_OBSOLETES`
`CPACK_RPM_<component>_PACKAGE_OBSOLETES`
RPM spec obsoletes field.
* Mandatory : NO
* Default : -
May be used to set RPM packages that are obsoleted by this one.
`CPACK_RPM_PACKAGE_RELOCATABLE`
build a relocatable RPM.
* Mandatory : NO
* Default : CPACK\_PACKAGE\_RELOCATABLE
If this variable is set to TRUE or ON CPackRPM will try to build a relocatable RPM package. A relocatable RPM may be installed using:
```
rpm --prefix or --relocate
```
in order to install it at an alternate place see rpm(8). Note that currently this may fail if [`CPACK_SET_DESTDIR`](../variable/cpack_set_destdir#variable:CPACK_SET_DESTDIR "CPACK_SET_DESTDIR") is set to `ON`. If [`CPACK_SET_DESTDIR`](../variable/cpack_set_destdir#variable:CPACK_SET_DESTDIR "CPACK_SET_DESTDIR") is set then you will get a warning message but if there is file installed with absolute path you’ll get unexpected behavior.
`CPACK_RPM_SPEC_INSTALL_POST`
Deprecated - use [`CPACK_RPM_POST_INSTALL_SCRIPT_FILE`](#variable:CPACK_RPM_POST_INSTALL_SCRIPT_FILE "CPACK_RPM_POST_INSTALL_SCRIPT_FILE") instead.
* Mandatory : NO
* Default : -
* Deprecated: YES
This way of specifying post-install script is deprecated, use [`CPACK_RPM_POST_INSTALL_SCRIPT_FILE`](#variable:CPACK_RPM_POST_INSTALL_SCRIPT_FILE "CPACK_RPM_POST_INSTALL_SCRIPT_FILE"). May be used to set an RPM post-install command inside the spec file. For example setting it to `/bin/true` may be used to prevent rpmbuild to strip binaries.
`CPACK_RPM_SPEC_MORE_DEFINE`
RPM extended spec definitions lines.
* Mandatory : NO
* Default : -
May be used to add any `%define` lines to the generated spec file.
`CPACK_RPM_PACKAGE_DEBUG`
Toggle CPackRPM debug output.
* Mandatory : NO
* Default : -
May be set when invoking cpack in order to trace debug information during CPack RPM run. For example you may launch CPack like this:
```
cpack -D CPACK_RPM_PACKAGE_DEBUG=1 -G RPM
```
`CPACK_RPM_USER_BINARY_SPECFILE`
`CPACK_RPM_<componentName>_USER_BINARY_SPECFILE`
A user provided spec file.
* Mandatory : NO
* Default : -
May be set by the user in order to specify a USER binary spec file to be used by CPackRPM instead of generating the file. The specified file will be processed by configure\_file( @ONLY).
`CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE`
Spec file template.
* Mandatory : NO
* Default : -
If set CPack will generate a template for USER specified binary spec file and stop with an error. For example launch CPack like this:
```
cpack -D CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE=1 -G RPM
```
The user may then use this file in order to hand-craft is own binary spec file which may be used with [`CPACK_RPM_USER_BINARY_SPECFILE`](#variable:CPACK_RPM_USER_BINARY_SPECFILE "CPACK_RPM_USER_BINARY_SPECFILE").
`CPACK_RPM_PRE_INSTALL_SCRIPT_FILE`
`CPACK_RPM_PRE_UNINSTALL_SCRIPT_FILE`
Path to file containing pre (un)install script.
* Mandatory : NO
* Default : -
May be used to embed a pre (un)installation script in the spec file. The referred script file (or both) will be read and directly put after the `%pre` or `%preun` section If [`CPACK_RPM_COMPONENT_INSTALL`](#variable:CPACK_RPM_COMPONENT_INSTALL "CPACK_RPM_COMPONENT_INSTALL") is set to ON the (un)install script for each component can be overridden with `CPACK_RPM_<COMPONENT>_PRE_INSTALL_SCRIPT_FILE` and `CPACK_RPM_<COMPONENT>_PRE_UNINSTALL_SCRIPT_FILE`. One may verify which scriptlet has been included with:
```
rpm -qp --scripts package.rpm
```
`CPACK_RPM_POST_INSTALL_SCRIPT_FILE`
`CPACK_RPM_POST_UNINSTALL_SCRIPT_FILE`
Path to file containing post (un)install script.
* Mandatory : NO
* Default : -
May be used to embed a post (un)installation script in the spec file. The referred script file (or both) will be read and directly put after the `%post` or `%postun` section. If [`CPACK_RPM_COMPONENT_INSTALL`](#variable:CPACK_RPM_COMPONENT_INSTALL "CPACK_RPM_COMPONENT_INSTALL") is set to ON the (un)install script for each component can be overridden with `CPACK_RPM_<COMPONENT>_POST_INSTALL_SCRIPT_FILE` and `CPACK_RPM_<COMPONENT>_POST_UNINSTALL_SCRIPT_FILE`. One may verify which scriptlet has been included with:
```
rpm -qp --scripts package.rpm
```
`CPACK_RPM_USER_FILELIST`
`CPACK_RPM_<COMPONENT>_USER_FILELIST`
* Mandatory : NO
* Default : -
May be used to explicitly specify `%(<directive>)` file line in the spec file. Like `%config(noreplace)` or any other directive that be found in the `%files` section. You can have multiple directives per line, as in `%attr(600,root,root) %config(noreplace)`. Since CPackRPM is generating the list of files (and directories) the user specified files of the `CPACK_RPM_<COMPONENT>_USER_FILELIST` list will be removed from the generated list. If referring to directories do not add a trailing slash.
`CPACK_RPM_CHANGELOG_FILE`
RPM changelog file.
* Mandatory : NO
* Default : -
May be used to embed a changelog in the spec file. The referred file will be read and directly put after the `%changelog` section.
`CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST`
list of path to be excluded.
* Mandatory : NO
* Default : /etc /etc/init.d /usr /usr/share /usr/share/doc /usr/bin /usr/lib /usr/lib64 /usr/include
May be used to exclude path (directories or files) from the auto-generated list of paths discovered by CPack RPM. The defaut value contains a reasonable set of values if the variable is not defined by the user. If the variable is defined by the user then CPackRPM will NOT any of the default path. If you want to add some path to the default list then you can use [`CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION`](#variable:CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION "CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION") variable.
`CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION`
additional list of path to be excluded.
* Mandatory : NO
* Default : -
May be used to add more exclude path (directories or files) from the initial default list of excluded paths. See [`CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST`](#variable:CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST "CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST").
`CPACK_RPM_RELOCATION_PATHS`
Packages relocation paths list.
* Mandatory : NO
* Default : -
May be used to specify more than one relocation path per relocatable RPM. Variable contains a list of relocation paths that if relative are prefixed by the value of [`CPACK_RPM_<COMPONENT>_PACKAGE_PREFIX`](#variable:CPACK_RPM_<COMPONENT>_PACKAGE_PREFIX "CPACK_RPM_<COMPONENT>_PACKAGE_PREFIX") or by the value of [`CPACK_PACKAGING_INSTALL_PREFIX`](../variable/cpack_packaging_install_prefix#variable:CPACK_PACKAGING_INSTALL_PREFIX "CPACK_PACKAGING_INSTALL_PREFIX") if the component version is not provided. Variable is not component based as its content can be used to set a different path prefix for e.g. binary dir and documentation dir at the same time. Only prefixes that are required by a certain component are added to that component - component must contain at least one file/directory/symbolic link with [`CPACK_RPM_RELOCATION_PATHS`](#variable:CPACK_RPM_RELOCATION_PATHS "CPACK_RPM_RELOCATION_PATHS") prefix for a certain relocation path to be added. Package will not contain any relocation paths if there are no files/directories/symbolic links on any of the provided prefix locations. Packages that either do not contain any relocation paths or contain files/directories/symbolic links that are outside relocation paths print out an `AUTHOR_WARNING` that RPM will be partially relocatable.
`CPACK_RPM_<COMPONENT>_PACKAGE_PREFIX`
Per component relocation path install prefix.
* Mandatory : NO
* Default : CPACK\_PACKAGING\_INSTALL\_PREFIX
May be used to set per component [`CPACK_PACKAGING_INSTALL_PREFIX`](../variable/cpack_packaging_install_prefix#variable:CPACK_PACKAGING_INSTALL_PREFIX "CPACK_PACKAGING_INSTALL_PREFIX") for relocatable RPM packages.
`CPACK_RPM_NO_INSTALL_PREFIX_RELOCATION`
`CPACK_RPM_NO_<COMPONENT>_INSTALL_PREFIX_RELOCATION`
Removal of default install prefix from relocation paths list.
* Mandatory : NO
* `Default : CPACK_PACKAGING_INSTALL_PREFIX or CPACK_RPM_<COMPONENT>_PACKAGE_PREFIX` are treated as one of relocation paths
May be used to remove CPACK\_PACKAGING\_INSTALL\_PREFIX and CPACK\_RPM\_<COMPONENT>\_PACKAGE\_PREFIX from relocatable RPM prefix paths.
`CPACK_RPM_ADDITIONAL_MAN_DIRS`
* Mandatory : NO
* Default : -
May be used to set additional man dirs that could potentially be compressed by brp-compress RPM macro. Variable content must be a list of regular expressions that point to directories containing man files or to man files directly. Note that in order to compress man pages a path must also be present in brp-compress RPM script and that brp-compress script must be added to RPM configuration by the operating system.
Regular expressions that are added by default were taken from brp-compress RPM macro:
* /usr/man/man.\*
* /usr/man/.\*/man.\*
* /usr/info.\*
* /usr/share/man/man.\*
* /usr/share/man/.\*/man.\*
* /usr/share/info.\*
* /usr/kerberos/man.\*
* /usr/X11R6/man/man.\*
* /usr/lib/perl5/man/man.\*
* /usr/share/doc/.\*/man/man.\*
* /usr/lib/.\*/man/man.\*
`CPACK_RPM_DEFAULT_USER`
`CPACK_RPM_<compName>_DEFAULT_USER`
default user ownership of RPM content
* Mandatory : NO
* Default : root
Value should be user name and not UID. Note that <compName> must be in upper-case.
`CPACK_RPM_DEFAULT_GROUP`
`CPACK_RPM_<compName>_DEFAULT_GROUP`
default group ownership of RPM content
* Mandatory : NO
* Default : root
Value should be group name and not GID. Note that <compName> must be in upper-case.
`CPACK_RPM_DEFAULT_FILE_PERMISSIONS`
`CPACK_RPM_<compName>_DEFAULT_FILE_PERMISSIONS`
default permissions used for packaged files
* Mandatory : NO
* Default : - (system default)
Accepted values are lists with `PERMISSIONS`. Valid permissions are:
* OWNER\_READ
* OWNER\_WRITE
* OWNER\_EXECUTE
* GROUP\_READ
* GROUP\_WRITE
* GROUP\_EXECUTE
* WORLD\_READ
* WORLD\_WRITE
* WORLD\_EXECUTE
Note that <compName> must be in upper-case.
`CPACK_RPM_DEFAULT_DIR_PERMISSIONS`
`CPACK_RPM_<compName>_DEFAULT_DIR_PERMISSIONS`
default permissions used for packaged directories
* Mandatory : NO
* Default : - (system default)
Accepted values are lists with PERMISSIONS. Valid permissions are the same as for [`CPACK_RPM_DEFAULT_FILE_PERMISSIONS`](#variable:CPACK_RPM_DEFAULT_FILE_PERMISSIONS "CPACK_RPM_DEFAULT_FILE_PERMISSIONS"). Note that <compName> must be in upper-case.
Packaging of Symbolic Links
---------------------------
CPackRPM supports packaging of symbolic links:
```
execute_process(COMMAND ${CMAKE_COMMAND}
-E create_symlink <relative_path_location> <symlink_name>)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/<symlink_name>
DESTINATION <symlink_location> COMPONENT libraries)
```
Symbolic links will be optimized (paths will be shortened if possible) before being added to the package or if multiple relocation paths are detected, a post install symlink relocation script will be generated.
Symbolic links may point to locations that are not packaged by the same package (either a different component or even not packaged at all) but those locations will be treated as if they were a part of the package while determining if symlink should be either created or present in a post install script - depending on relocation paths.
Symbolic links that point to locations outside packaging path produce a warning and are treated as non relocatable permanent symbolic links.
Currently there are a few limitations though:
* For component based packaging component interdependency is not checked when processing symbolic links. Symbolic links pointing to content of a different component are treated the same way as if pointing to location that will not be packaged.
* Symbolic links pointing to a location through one or more intermediate symbolic links will not be handled differently - if the intermediate symbolic link(s) is also on a relocatable path, relocating it during package installation may cause initial symbolic link to point to an invalid location.
Packaging of debug information
------------------------------
Debuginfo packages contain debug symbols and sources for debugging packaged binaries.
Debuginfo RPM packaging has it’s own set of variables:
`CPACK_RPM_DEBUGINFO_PACKAGE`
`CPACK_RPM_<component>_DEBUGINFO_PACKAGE`
Enable generation of debuginfo RPM package(s).
* Mandatory : NO
* Default : OFF
Note
Binaries must contain debug symbols before packaging so use either `Debug` or `RelWithDebInfo` for [`CMAKE_BUILD_TYPE`](../variable/cmake_build_type#variable:CMAKE_BUILD_TYPE "CMAKE_BUILD_TYPE") variable value.
Note
Packages generated from packages without binary files, with binary files but without execute permissions or without debug symbols will be empty.
`CPACK_BUILD_SOURCE_DIRS`
Provides locations of root directories of source files from which binaries were built.
* Mandatory : YES if [`CPACK_RPM_DEBUGINFO_PACKAGE`](#variable:CPACK_RPM_DEBUGINFO_PACKAGE "CPACK_RPM_DEBUGINFO_PACKAGE") is set
* Default : -
Note
For CMake project [`CPACK_BUILD_SOURCE_DIRS`](#variable:CPACK_BUILD_SOURCE_DIRS "CPACK_BUILD_SOURCE_DIRS") is set by default to point to [`CMAKE_SOURCE_DIR`](../variable/cmake_source_dir#variable:CMAKE_SOURCE_DIR "CMAKE_SOURCE_DIR") and [`CMAKE_BINARY_DIR`](../variable/cmake_binary_dir#variable:CMAKE_BINARY_DIR "CMAKE_BINARY_DIR") paths.
Note
Sources with path prefixes that do not fall under any location provided with [`CPACK_BUILD_SOURCE_DIRS`](#variable:CPACK_BUILD_SOURCE_DIRS "CPACK_BUILD_SOURCE_DIRS") will not be present in debuginfo package.
`CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX`
`CPACK_RPM_<component>_BUILD_SOURCE_DIRS_PREFIX`
Prefix of location where sources will be placed during package installation.
* Mandatory : YES if [`CPACK_RPM_DEBUGINFO_PACKAGE`](#variable:CPACK_RPM_DEBUGINFO_PACKAGE "CPACK_RPM_DEBUGINFO_PACKAGE") is set
* `Default : “/usr/src/debug/<CPACK_PACKAGE_FILE_NAME>” and` for component packaging “/usr/src/debug/<CPACK\_PACKAGE\_FILE\_NAME>-<component>”
Note
Each source path prefix is additionaly suffixed by `src_<index>` where index is index of the path used from [`CPACK_BUILD_SOURCE_DIRS`](#variable:CPACK_BUILD_SOURCE_DIRS "CPACK_BUILD_SOURCE_DIRS") variable. This produces `<CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX>/src_<index>` replacement path. Limitation is that replaced path part must be shorter or of equal length than the length of its replacement. If that is not the case either [`CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX`](#variable:CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX "CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX") variable has to be set to a shorter path or source directories must be placed on a longer path.
`CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS`
Directories containing sources that should be excluded from debuginfo packages.
* Mandatory : NO
* Default : “/usr /usr/src /usr/src/debug”
Listed paths are owned by other RPM packages and should therefore not be deleted on debuginfo package uninstallation.
`CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS_ADDITION`
Paths that should be appended to [`CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS`](#variable:CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS "CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS") for exclusion.
* Mandatory : NO
* Default : -
`CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE`
Create a single debuginfo package even if components packaging is set.
* Mandatory : NO
* Default : OFF
When this variable is enabled it produces a single debuginfo package even if component packaging is enabled.
When using this feature in combination with components packaging and there is more than one component this variable requires [`CPACK_RPM_MAIN_COMPONENT`](#variable:CPACK_RPM_MAIN_COMPONENT "CPACK_RPM_MAIN_COMPONENT") to be set.
Note
If none of the [`CPACK_RPM_<component>_DEBUGINFO_PACKAGE`](#variable:CPACK_RPM_<component>_DEBUGINFO_PACKAGE "CPACK_RPM_<component>_DEBUGINFO_PACKAGE") variables is set then [`CPACK_RPM_DEBUGINFO_PACKAGE`](#variable:CPACK_RPM_DEBUGINFO_PACKAGE "CPACK_RPM_DEBUGINFO_PACKAGE") is automatically set to `ON` when [`CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE`](#variable:CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE "CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE") is set.
`CPACK_RPM_DEBUGINFO_FILE_NAME`
`CPACK_RPM_<component>_DEBUGINFO_FILE_NAME`
Debuginfo package file name.
* Mandatory : NO
* Default : rpmbuild tool generated package file name
Alternatively provided debuginfo package file name must end with `.rpm` suffix and should differ from file names of other generated packages.
Variable may contain `@cpack_component@` placeholder which will be replaced by component name if component packaging is enabled otherwise it deletes the placeholder.
Setting the variable to `RPM-DEFAULT` may be used to explicitly set filename generation to default.
Note
[`CPACK_RPM_FILE_NAME`](#variable:CPACK_RPM_FILE_NAME "CPACK_RPM_FILE_NAME") also supports rpmbuild tool generated package file name - disabled by default but can be enabled by setting the variable to `RPM-DEFAULT`.
Packaging of sources (SRPM)
---------------------------
SRPM packaging is enabled by setting [`CPACK_RPM_PACKAGE_SOURCES`](#variable:CPACK_RPM_PACKAGE_SOURCES "CPACK_RPM_PACKAGE_SOURCES") variable while usually using [`CPACK_INSTALLED_DIRECTORIES`](cpack#variable:CPACK_INSTALLED_DIRECTORIES "CPACK_INSTALLED_DIRECTORIES") variable to provide directory containing CMakeLists.txt and source files.
For CMake projects SRPM package would be product by executing:
`cpack -G RPM --config ./CPackSourceConfig.cmake`
Note
Produced SRPM package is expected to be built with [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") executable and packaged with [`cpack(1)`](../manual/cpack.1#manual:cpack(1) "cpack(1)") executable so CMakeLists.txt has to be located in root source directory and must be able to generate binary rpm packages by executing `cpack -G` command. The two executables as well as rpmbuild must also be present when generating binary rpm packages from the produced SRPM package.
Once the SRPM package is generated it can be used to generate binary packages by creating a directory structure for rpm generation and executing rpmbuild tool:
`mkdir -p build_dir/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}` `rpmbuild --define "_topdir <path_to_build_dir>" --rebuild <SRPM_file_name>`
Generated packages will be located in build\_dir/RPMS directory or its sub directories.
Note
SRPM package internally uses CPack/RPM generator to generate binary packages so CMakeScripts.txt can decide during the SRPM to binary rpm generation step what content the package(s) should have as well as how they should be packaged (monolithic or components). CMake can decide this for e.g. by reading environment variables set by the package manager before starting the process of generating binary rpm packages. This way a single SRPM package can be used to produce different binary rpm packages on different platforms depending on the platform’s packaging rules.
Source RPM packaging has it’s own set of variables:
`CPACK_RPM_PACKAGE_SOURCES`
Should the content be packaged as a source rpm (default is binary rpm).
* Mandatory : NO
* Default : OFF
Note
For cmake projects [`CPACK_RPM_PACKAGE_SOURCES`](#variable:CPACK_RPM_PACKAGE_SOURCES "CPACK_RPM_PACKAGE_SOURCES") variable is set to `OFF` in CPackConfig.cmake and `ON` in CPackSourceConfig.cmake generated files.
`CPACK_RPM_SOURCE_PKG_BUILD_PARAMS`
Additional command-line parameters provided to [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") executable.
* Mandatory : NO
* Default : -
`CPACK_RPM_SOURCE_PKG_PACKAGING_INSTALL_PREFIX`
Packaging install prefix that would be provided in [`CPACK_PACKAGING_INSTALL_PREFIX`](../variable/cpack_packaging_install_prefix#variable:CPACK_PACKAGING_INSTALL_PREFIX "CPACK_PACKAGING_INSTALL_PREFIX") variable for producing binary RPM packages.
* Mandatory : YES
* Default : “/”
`CPACK_RPM_BUILDREQUIRES`
List of source rpm build dependencies.
* Mandatory : NO
* Default : -
May be used to set source RPM build dependencies (BuildRequires). Note that you must enclose the complete build requirements string between quotes, for example:
```
set(CPACK_RPM_BUILDREQUIRES "python >= 2.5.0, cmake >= 2.8")
```
| programming_docs |
cmake FindosgWidget FindosgWidget
=============
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgWidget This module defines
OSGWIDGET\_FOUND - Was osgWidget found? OSGWIDGET\_INCLUDE\_DIR - Where to find the headers OSGWIDGET\_LIBRARIES - The libraries to link for osgWidget (use this)
OSGWIDGET\_LIBRARY - The osgWidget library OSGWIDGET\_LIBRARY\_DEBUG - The osgWidget debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
FindosgWidget.cmake tweaked from Findosg\* suite as created by Eric Wing.
cmake FindosgText FindosgText
===========
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgText This module defines
OSGTEXT\_FOUND - Was osgText found? OSGTEXT\_INCLUDE\_DIR - Where to find the headers OSGTEXT\_LIBRARIES - The libraries to link for osgText (use this)
OSGTEXT\_LIBRARY - The osgText library OSGTEXT\_LIBRARY\_DEBUG - The osgText debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake FindosgVolume FindosgVolume
=============
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgVolume This module defines
OSGVOLUME\_FOUND - Was osgVolume found? OSGVOLUME\_INCLUDE\_DIR - Where to find the headers OSGVOLUME\_LIBRARIES - The libraries to link for osgVolume (use this)
OSGVOLUME\_LIBRARY - The osgVolume library OSGVOLUME\_LIBRARY\_DEBUG - The osgVolume debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake InstallRequiredSystemLibraries InstallRequiredSystemLibraries
==============================
Include this module to search for compiler-provided system runtime libraries and add install rules for them. Some optional variables may be set prior to including the module to adjust behavior:
`CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS` Specify additional runtime libraries that may not be detected. After inclusion any detected libraries will be appended to this.
`CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_SKIP` Set to TRUE to skip calling the [`install(PROGRAMS)`](../command/install#command:install "install") command to allow the includer to specify its own install rule, using the value of `CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS` to get the list of libraries.
`CMAKE_INSTALL_DEBUG_LIBRARIES` Set to TRUE to install the debug runtime libraries when available with MSVC tools.
`CMAKE_INSTALL_DEBUG_LIBRARIES_ONLY` Set to TRUE to install only the debug runtime libraries with MSVC tools even if the release runtime libraries are also available.
`CMAKE_INSTALL_UCRT_LIBRARIES`
Set to TRUE to install the Windows Universal CRT libraries for app-local deployment (e.g. to Windows XP). This is meaningful only with MSVC from Visual Studio 2015 or higher.
One may set a `CMAKE_WINDOWS_KITS_10_DIR` *environment variable* to an absolute path to tell CMake to look for Windows 10 SDKs in a custom location. The specified directory is expected to contain `Redist/ucrt/DLLs/*` directories.
`CMAKE_INSTALL_MFC_LIBRARIES` Set to TRUE to install the MSVC MFC runtime libraries.
`CMAKE_INSTALL_OPENMP_LIBRARIES` Set to TRUE to install the MSVC OpenMP runtime libraries
`CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION` Specify the [`install(PROGRAMS)`](../command/install#command:install "install") command `DESTINATION` option. If not specified, the default is `bin` on Windows and `lib` elsewhere.
`CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS` Set to TRUE to disable warnings about required library files that do not exist. (For example, Visual Studio Express editions may not provide the redistributable files.)
`CMAKE_INSTALL_SYSTEM_RUNTIME_COMPONENT` Specify the [`install(PROGRAMS)`](../command/install#command:install "install") command `COMPONENT` option. If not specified, no such option will be used.
cmake FindCxxTest FindCxxTest
===========
Find CxxTest
Find the CxxTest suite and declare a helper macro for creating unit tests and integrating them with CTest. For more details on CxxTest see <http://cxxtest.tigris.org>
INPUT Variables
```
CXXTEST_USE_PYTHON [deprecated since 1.3]
Only used in the case both Python & Perl
are detected on the system to control
which CxxTest code generator is used.
Valid only for CxxTest version 3.
```
```
NOTE: In older versions of this Find Module,
this variable controlled if the Python test
generator was used instead of the Perl one,
regardless of which scripting language the
user had installed.
```
```
CXXTEST_TESTGEN_ARGS (since CMake 2.8.3)
Specify a list of options to pass to the CxxTest code
generator. If not defined, --error-printer is
passed.
```
OUTPUT Variables
```
CXXTEST_FOUND
True if the CxxTest framework was found
CXXTEST_INCLUDE_DIRS
Where to find the CxxTest include directory
CXXTEST_PERL_TESTGEN_EXECUTABLE
The perl-based test generator
CXXTEST_PYTHON_TESTGEN_EXECUTABLE
The python-based test generator
CXXTEST_TESTGEN_EXECUTABLE (since CMake 2.8.3)
The test generator that is actually used (chosen using user preferences
and interpreters found in the system)
CXXTEST_TESTGEN_INTERPRETER (since CMake 2.8.3)
The full path to the Perl or Python executable on the system, on
platforms where the script cannot be executed using its shebang line.
```
MACROS for optional use by CMake users:
```
CXXTEST_ADD_TEST(<test_name> <gen_source_file> <input_files_to_testgen...>)
Creates a CxxTest runner and adds it to the CTest testing suite
Parameters:
test_name The name of the test
gen_source_file The generated source filename to be
generated by CxxTest
input_files_to_testgen The list of header files containing the
CxxTest::TestSuite's to be included in
this runner
```
```
#==============
Example Usage:
```
```
find_package(CxxTest)
if(CXXTEST_FOUND)
include_directories(${CXXTEST_INCLUDE_DIR})
enable_testing()
```
```
CXXTEST_ADD_TEST(unittest_foo foo_test.cc
${CMAKE_CURRENT_SOURCE_DIR}/foo_test.h)
target_link_libraries(unittest_foo foo) # as needed
endif()
```
```
This will (if CxxTest is found):
1. Invoke the testgen executable to autogenerate foo_test.cc in the
binary tree from "foo_test.h" in the current source directory.
2. Create an executable and test called unittest_foo.
```
```
#=============
Example foo_test.h:
```
```
#include <cxxtest/TestSuite.h>
```
```
class MyTestSuite : public CxxTest::TestSuite
{
public:
void testAddition( void )
{
TS_ASSERT( 1 + 1 > 1 );
TS_ASSERT_EQUALS( 1 + 1, 2 );
}
};
```
cmake MacroAddFileDependencies MacroAddFileDependencies
========================
MACRO\_ADD\_FILE\_DEPENDENCIES(<\_file> depend\_files…)
Using the macro MACRO\_ADD\_FILE\_DEPENDENCIES() is discouraged. There are usually better ways to specify the correct dependencies.
MACRO\_ADD\_FILE\_DEPENDENCIES(<\_file> depend\_files…) is just a convenience wrapper around the OBJECT\_DEPENDS source file property. You can just use set\_property(SOURCE <file> APPEND PROPERTY OBJECT\_DEPENDS depend\_files) instead.
cmake FindCVS FindCVS
=======
The module defines the following variables:
```
CVS_EXECUTABLE - path to cvs command line client
CVS_FOUND - true if the command line client was found
```
Example usage:
```
find_package(CVS)
if(CVS_FOUND)
message("CVS found: ${CVS_EXECUTABLE}")
endif()
```
cmake TestForANSIForScope TestForANSIForScope
===================
Check for ANSI for scope support
Check if the compiler restricts the scope of variables declared in a for-init-statement to the loop body.
```
CMAKE_NO_ANSI_FOR_SCOPE - holds result
```
cmake CPackDeb CPackDeb
========
The built in (binary) CPack Deb generator (Unix only)
Variables specific to CPack Debian (DEB) generator
--------------------------------------------------
CPackDeb may be used to create Deb package using [`CPack`](cpack#module:CPack "CPack"). CPackDeb is a [`CPack`](cpack#module:CPack "CPack") generator thus it uses the `CPACK_XXX` variables used by [`CPack`](cpack#module:CPack "CPack").
CPackDeb generator should work on any Linux host but it will produce better deb package when Debian specific tools `dpkg-xxx` are usable on the build system.
CPackDeb has specific features which are controlled by the specifics `CPACK_DEBIAN_XXX` variables.
`CPACK_DEBIAN_<COMPONENT>_XXXX` variables may be used in order to have **component** specific values. Note however that `<COMPONENT>` refers to the **grouping name** written in upper case. It may be either a component name or a component GROUP name.
Here are some CPackDeb wiki resources that are here for historic reasons and are no longer maintained but may still prove useful:
* <https://cmake.org/Wiki/CMake:CPackConfiguration>
* <https://cmake.org/Wiki/CMake:CPackPackageGenerators#DEB_.28UNIX_only.29>
List of CPackDEB specific variables:
`CPACK_DEB_COMPONENT_INSTALL`
Enable component packaging for CPackDEB
* Mandatory : NO
* Default : OFF
If enabled (ON) multiple packages are generated. By default a single package containing files of all components is generated.
`CPACK_DEBIAN_PACKAGE_NAME`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_NAME`
Set Package control field (variable is automatically transformed to lower case).
* Mandatory : YES
* Default :
+ [`CPACK_PACKAGE_NAME`](cpack#variable:CPACK_PACKAGE_NAME "CPACK_PACKAGE_NAME") for non-component based installations
+ [`CPACK_DEBIAN_PACKAGE_NAME`](#variable:CPACK_DEBIAN_PACKAGE_NAME "CPACK_DEBIAN_PACKAGE_NAME") suffixed with -<COMPONENT> for component-based installations.
See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Source>
`CPACK_DEBIAN_FILE_NAME`
`CPACK_DEBIAN_<COMPONENT>_FILE_NAME`
Package file name.
* Mandatory : YES
* Default : `<CPACK_PACKAGE_FILE_NAME>[-<component>].deb`
This may be set to `DEB-DEFAULT` to allow CPackDeb to generate package file name by itself in deb format:
```
<PackageName>_<VersionNumber>-<DebianRevisionNumber>_<DebianArchitecture>.deb
```
Alternatively provided package file name must end with `.deb` suffix.
Note
Preferred setting of this variable is `DEB-DEFAULT` but for backward compatibility with CPackDeb in CMake prior to version 3.6 this feature is disabled by default.
Note
By using non default filenames duplicate names may occur. Duplicate files get overwritten and it is up to the packager to set the variables in a manner that will prevent such errors.
`CPACK_DEBIAN_PACKAGE_VERSION`
The Debian package version
* Mandatory : YES
* Default : [`CPACK_PACKAGE_VERSION`](cpack#variable:CPACK_PACKAGE_VERSION "CPACK_PACKAGE_VERSION")
`CPACK_DEBIAN_PACKAGE_RELEASE`
The Debian package release - Debian revision number.
* Mandatory : YES
* Default : 1
This is the numbering of the DEB package itself, i.e. the version of the packaging and not the version of the content (see [`CPACK_DEBIAN_PACKAGE_VERSION`](#variable:CPACK_DEBIAN_PACKAGE_VERSION "CPACK_DEBIAN_PACKAGE_VERSION")). One may change the default value if the previous packaging was buggy and/or you want to put here a fancy Linux distro specific numbering.
`CPACK_DEBIAN_PACKAGE_ARCHITECTURE`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_ARCHITECTURE`
The Debian package architecture
* Mandatory : YES
* Default : Output of `dpkg --print-architecture` (or `i386` if `dpkg` is not found)
`CPACK_DEBIAN_PACKAGE_DEPENDS`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_DEPENDS`
Sets the Debian dependencies of this package.
* Mandatory : NO
* Default :
+ An empty string for non-component based installations
+ [`CPACK_DEBIAN_PACKAGE_DEPENDS`](#variable:CPACK_DEBIAN_PACKAGE_DEPENDS "CPACK_DEBIAN_PACKAGE_DEPENDS") for component-based installations.
Note
If [`CPACK_DEBIAN_PACKAGE_SHLIBDEPS`](#variable:CPACK_DEBIAN_PACKAGE_SHLIBDEPS "CPACK_DEBIAN_PACKAGE_SHLIBDEPS") or more specifically [`CPACK_DEBIAN_<COMPONENT>_PACKAGE_SHLIBDEPS`](#variable:CPACK_DEBIAN_<COMPONENT>_PACKAGE_SHLIBDEPS "CPACK_DEBIAN_<COMPONENT>_PACKAGE_SHLIBDEPS") is set for this component, the discovered dependencies will be appended to [`CPACK_DEBIAN_<COMPONENT>_PACKAGE_DEPENDS`](#variable:CPACK_DEBIAN_<COMPONENT>_PACKAGE_DEPENDS "CPACK_DEBIAN_<COMPONENT>_PACKAGE_DEPENDS") instead of [`CPACK_DEBIAN_PACKAGE_DEPENDS`](#variable:CPACK_DEBIAN_PACKAGE_DEPENDS "CPACK_DEBIAN_PACKAGE_DEPENDS"). If [`CPACK_DEBIAN_<COMPONENT>_PACKAGE_DEPENDS`](#variable:CPACK_DEBIAN_<COMPONENT>_PACKAGE_DEPENDS "CPACK_DEBIAN_<COMPONENT>_PACKAGE_DEPENDS") is an empty string, only the automatically discovered dependencies will be set for this component.
Example:
```
set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6 (>= 2.3.1-6), libc6 (< 2.4)")
```
`CPACK_DEBIAN_ENABLE_COMPONENT_DEPENDS`
Sets inter component dependencies if listed with [`CPACK_COMPONENT_<compName>_DEPENDS`](# "CPACK_COMPONENT_<compName>_DEPENDS") variables.
* Mandatory : NO
* Default : -
`CPACK_DEBIAN_PACKAGE_MAINTAINER`
The Debian package maintainer
* Mandatory : YES
* Default : `CPACK_PACKAGE_CONTACT`
`CPACK_DEBIAN_PACKAGE_DESCRIPTION`
`CPACK_COMPONENT_<COMPONENT>_DESCRIPTION`
The Debian package description
* Mandatory : YES
* Default :
+ [`CPACK_DEBIAN_PACKAGE_DESCRIPTION`](#variable:CPACK_DEBIAN_PACKAGE_DESCRIPTION "CPACK_DEBIAN_PACKAGE_DESCRIPTION") if set or
+ [`CPACK_PACKAGE_DESCRIPTION_SUMMARY`](cpack#variable:CPACK_PACKAGE_DESCRIPTION_SUMMARY "CPACK_PACKAGE_DESCRIPTION_SUMMARY")
`CPACK_DEBIAN_PACKAGE_SECTION`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_SECTION`
Set Section control field e.g. admin, devel, doc, …
* Mandatory : YES
* Default : “devel”
See <https://www.debian.org/doc/debian-policy/ch-archive.html#s-subsections>
`CPACK_DEBIAN_ARCHIVE_TYPE`
The archive format used for creating the Debian package.
* Mandatory : YES
* Default : “paxr”
Possible values are:
* paxr
* gnutar
Note
Default pax archive format is the most portable format and generates packages that do not treat sparse files specially. GNU tar format on the other hand supports longer filenames.
`CPACK_DEBIAN_COMPRESSION_TYPE`
The compression used for creating the Debian package.
* Mandatory : YES
* Default : “gzip”
Possible values are:
* lzma
* xz
* bzip2
* gzip
`CPACK_DEBIAN_PACKAGE_PRIORITY`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_PRIORITY`
Set Priority control field e.g. required, important, standard, optional, extra
* Mandatory : YES
* Default : “optional”
See <https://www.debian.org/doc/debian-policy/ch-archive.html#s-priorities>
`CPACK_DEBIAN_PACKAGE_HOMEPAGE`
The URL of the web site for this package, preferably (when applicable) the site from which the original source can be obtained and any additional upstream documentation or information may be found.
* Mandatory : NO
* Default : -
Note
The content of this field is a simple URL without any surrounding characters such as <>.
`CPACK_DEBIAN_PACKAGE_SHLIBDEPS`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_SHLIBDEPS`
May be set to ON in order to use `dpkg-shlibdeps` to generate better package dependency list.
* Mandatory : NO
* Default :
+ [`CPACK_DEBIAN_PACKAGE_SHLIBDEPS`](#variable:CPACK_DEBIAN_PACKAGE_SHLIBDEPS "CPACK_DEBIAN_PACKAGE_SHLIBDEPS") if set or
+ OFF
Note
You may need set [`CMAKE_INSTALL_RPATH`](../variable/cmake_install_rpath#variable:CMAKE_INSTALL_RPATH "CMAKE_INSTALL_RPATH") to an appropriate value if you use this feature, because if you don’t `dpkg-shlibdeps` may fail to find your own shared libs. See <https://cmake.org/Wiki/CMake_RPATH_handling>.
`CPACK_DEBIAN_PACKAGE_DEBUG`
May be set when invoking cpack in order to trace debug information during CPackDeb run.
* Mandatory : NO
* Default : -
`CPACK_DEBIAN_PACKAGE_PREDEPENDS`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_PREDEPENDS`
Sets the `Pre-Depends` field of the Debian package. Like [`Depends`](#variable:CPACK_DEBIAN_PACKAGE_DEPENDS "CPACK_DEBIAN_PACKAGE_DEPENDS"), except that it also forces `dpkg` to complete installation of the packages named before even starting the installation of the package which declares the pre-dependency.
* Mandatory : NO
* Default :
+ An empty string for non-component based installations
+ [`CPACK_DEBIAN_PACKAGE_PREDEPENDS`](#variable:CPACK_DEBIAN_PACKAGE_PREDEPENDS "CPACK_DEBIAN_PACKAGE_PREDEPENDS") for component-based installations.
See <http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps>
`CPACK_DEBIAN_PACKAGE_ENHANCES`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_ENHANCES`
Sets the `Enhances` field of the Debian package. Similar to [`Suggests`](#variable:CPACK_DEBIAN_PACKAGE_SUGGESTS "CPACK_DEBIAN_PACKAGE_SUGGESTS") but works in the opposite direction: declares that a package can enhance the functionality of another package.
* Mandatory : NO
* Default :
+ An empty string for non-component based installations
+ [`CPACK_DEBIAN_PACKAGE_ENHANCES`](#variable:CPACK_DEBIAN_PACKAGE_ENHANCES "CPACK_DEBIAN_PACKAGE_ENHANCES") for component-based installations.
See <http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps>
`CPACK_DEBIAN_PACKAGE_BREAKS`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_BREAKS`
Sets the `Breaks` field of the Debian package. When a binary package (P) declares that it breaks other packages (B), `dpkg` will not allow the package (P) which declares `Breaks` be **unpacked** unless the packages that will be broken (B) are deconfigured first. As long as the package (P) is configured, the previously deconfigured packages (B) cannot be reconfigured again.
* Mandatory : NO
* Default :
+ An empty string for non-component based installations
+ [`CPACK_DEBIAN_PACKAGE_BREAKS`](#variable:CPACK_DEBIAN_PACKAGE_BREAKS "CPACK_DEBIAN_PACKAGE_BREAKS") for component-based installations.
See <https://www.debian.org/doc/debian-policy/ch-relationships.html#s-breaks>
`CPACK_DEBIAN_PACKAGE_CONFLICTS`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_CONFLICTS`
Sets the `Conflicts` field of the Debian package. When one binary package declares a conflict with another using a `Conflicts` field, `dpkg` will not allow them to be unpacked on the system at the same time.
* Mandatory : NO
* Default :
+ An empty string for non-component based installations
+ [`CPACK_DEBIAN_PACKAGE_CONFLICTS`](#variable:CPACK_DEBIAN_PACKAGE_CONFLICTS "CPACK_DEBIAN_PACKAGE_CONFLICTS") for component-based installations.
See <https://www.debian.org/doc/debian-policy/ch-relationships.html#s-conflicts>
Note
This is a stronger restriction than [`Breaks`](#variable:CPACK_DEBIAN_PACKAGE_BREAKS "CPACK_DEBIAN_PACKAGE_BREAKS"), which prevents the broken package from being configured while the breaking package is in the “Unpacked” state but allows both packages to be unpacked at the same time.
`CPACK_DEBIAN_PACKAGE_PROVIDES`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_PROVIDES`
Sets the `Provides` field of the Debian package. A virtual package is one which appears in the `Provides` control field of another package.
* Mandatory : NO
* Default :
+ An empty string for non-component based installations
+ [`CPACK_DEBIAN_PACKAGE_PROVIDES`](#variable:CPACK_DEBIAN_PACKAGE_PROVIDES "CPACK_DEBIAN_PACKAGE_PROVIDES") for component-based installations.
See <https://www.debian.org/doc/debian-policy/ch-relationships.html#s-virtual>
`CPACK_DEBIAN_PACKAGE_REPLACES`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_REPLACES`
Sets the `Replaces` field of the Debian package. Packages can declare in their control file that they should overwrite files in certain other packages, or completely replace other packages.
* Mandatory : NO
* Default :
+ An empty string for non-component based installations
+ [`CPACK_DEBIAN_PACKAGE_REPLACES`](#variable:CPACK_DEBIAN_PACKAGE_REPLACES "CPACK_DEBIAN_PACKAGE_REPLACES") for component-based installations.
See <http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps>
`CPACK_DEBIAN_PACKAGE_RECOMMENDS`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_RECOMMENDS`
Sets the `Recommends` field of the Debian package. Allows packages to declare a strong, but not absolute, dependency on other packages.
* Mandatory : NO
* Default :
+ An empty string for non-component based installations
+ [`CPACK_DEBIAN_PACKAGE_RECOMMENDS`](#variable:CPACK_DEBIAN_PACKAGE_RECOMMENDS "CPACK_DEBIAN_PACKAGE_RECOMMENDS") for component-based installations.
See <http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps>
`CPACK_DEBIAN_PACKAGE_SUGGESTS`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_SUGGESTS`
Sets the `Suggests` field of the Debian package. Allows packages to declare a suggested package install grouping.
* Mandatory : NO
* Default :
+ An empty string for non-component based installations
+ [`CPACK_DEBIAN_PACKAGE_SUGGESTS`](#variable:CPACK_DEBIAN_PACKAGE_SUGGESTS "CPACK_DEBIAN_PACKAGE_SUGGESTS") for component-based installations.
See <http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps>
`CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS`
* Mandatory : NO
* Default : OFF
Allows to generate shlibs control file automatically. Compatibility is defined by [`CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS_POLICY`](#variable:CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS_POLICY "CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS_POLICY") variable value.
Note
Libraries are only considered if they have both library name and version set. This can be done by setting SOVERSION property with [`set_target_properties()`](../command/set_target_properties#command:set_target_properties "set_target_properties") command.
`CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS_POLICY`
Compatibility policy for auto-generated shlibs control file.
* Mandatory : NO
* Default : “=”
Defines compatibility policy for auto-generated shlibs control file. Possible values: “=”, “>=”
See <https://www.debian.org/doc/debian-policy/ch-sharedlibs.html#s-sharedlibs-shlibdeps>
`CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_CONTROL_EXTRA`
This variable allow advanced user to add custom script to the control.tar.gz. Typical usage is for conffiles, postinst, postrm, prerm.
* Mandatory : NO
* Default : -
Usage:
```
set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA
"${CMAKE_CURRENT_SOURCE_DIR/prerm;${CMAKE_CURRENT_SOURCE_DIR}/postrm")
```
Note
The original permissions of the files will be used in the final package unless the variable [`CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION`](#variable:CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION "CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION") is set. In particular, the scripts should have the proper executable flag prior to the generation of the package.
`CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_CONTROL_STRICT_PERMISSION`
This variable indicates if the Debian policy on control files should be strictly followed.
* Mandatory : NO
* Default : FALSE
Usage:
```
set(CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION TRUE)
```
Note
This overrides the permissions on the original files, following the rules set by Debian policy <https://www.debian.org/doc/debian-policy/ch-files.html#s-permissions-owners>
`CPACK_DEBIAN_PACKAGE_SOURCE`
`CPACK_DEBIAN_<COMPONENT>_PACKAGE_SOURCE`
Sets the `Source` field of the binary Debian package. When the binary package name is not the same as the source package name (in particular when several components/binaries are generated from one source) the source from which the binary has been generated should be indicated with the field `Source`.
* Mandatory : NO
* Default :
+ An empty string for non-component based installations
+ [`CPACK_DEBIAN_PACKAGE_SOURCE`](#variable:CPACK_DEBIAN_PACKAGE_SOURCE "CPACK_DEBIAN_PACKAGE_SOURCE") for component-based installations.
See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Source>
Note
This value is not interpreted. It is possible to pass an optional revision number of the referenced source package as well.
| programming_docs |
cmake FindSDL_ttf FindSDL\_ttf
============
Locate SDL\_ttf library
This module defines:
```
SDL_TTF_LIBRARIES, the name of the library to link against
SDL_TTF_INCLUDE_DIRS, where to find the headers
SDL_TTF_FOUND, if false, do not try to link against
SDL_TTF_VERSION_STRING - human-readable string containing the version of SDL_ttf
```
For backward compatibility the following variables are also set:
```
SDLTTF_LIBRARY (same value as SDL_TTF_LIBRARIES)
SDLTTF_INCLUDE_DIR (same value as SDL_TTF_INCLUDE_DIRS)
SDLTTF_FOUND (same value as SDL_TTF_FOUND)
```
$SDLDIR is an environment variable that would correspond to the ./configure –prefix=$SDLDIR used in building SDL.
Created by Eric Wing. This was influenced by the FindSDL.cmake module, but with modifications to recognize OS X frameworks and additional Unix paths (FreeBSD, etc).
cmake FindLua51 FindLua51
=========
Locate Lua library This module defines
```
LUA51_FOUND, if false, do not try to link to Lua
LUA_LIBRARIES
LUA_INCLUDE_DIR, where to find lua.h
LUA_VERSION_STRING, the version of Lua found (since CMake 2.8.8)
```
Note that the expected include convention is
```
#include "lua.h"
```
and not
```
#include <lua/lua.h>
```
This is because, the lua location is not standardized and may exist in locations other than lua/
cmake CMakeDetermineVSServicePack CMakeDetermineVSServicePack
===========================
Deprecated. Do not use.
The functionality of this module has been superseded by the [`CMAKE_<LANG>_COMPILER_VERSION`](# "CMAKE_<LANG>_COMPILER_VERSION") variable that contains the compiler version number.
Determine the Visual Studio service pack of the ‘cl’ in use.
Usage:
```
if(MSVC)
include(CMakeDetermineVSServicePack)
DetermineVSServicePack( my_service_pack )
if( my_service_pack )
message(STATUS "Detected: ${my_service_pack}")
endif()
endif()
```
Function DetermineVSServicePack sets the given variable to one of the following values or an empty string if unknown:
```
vc80, vc80sp1
vc90, vc90sp1
vc100, vc100sp1
vc110, vc110sp1, vc110sp2, vc110sp3, vc110sp4
```
cmake FindCurses FindCurses
==========
Find the curses or ncurses include file and library.
Result Variables
----------------
This module defines the following variables:
`CURSES_FOUND` True if Curses is found.
`CURSES_INCLUDE_DIRS` The include directories needed to use Curses.
`CURSES_LIBRARIES` The libraries needed to use Curses.
`CURSES_HAVE_CURSES_H` True if curses.h is available.
`CURSES_HAVE_NCURSES_H` True if ncurses.h is available.
`CURSES_HAVE_NCURSES_NCURSES_H` True if `ncurses/ncurses.h` is available.
`CURSES_HAVE_NCURSES_CURSES_H` True if `ncurses/curses.h` is available. Set `CURSES_NEED_NCURSES` to `TRUE` before the `find_package(Curses)` call if NCurses functionality is required.
Backward Compatibility
----------------------
The following variable are provided for backward compatibility:
`CURSES_INCLUDE_DIR` Path to Curses include. Use `CURSES_INCLUDE_DIRS` instead.
`CURSES_LIBRARY` Path to Curses library. Use `CURSES_LIBRARIES` instead.
cmake FindTCL FindTCL
=======
TK\_INTERNAL\_PATH was removed.
This module finds if Tcl is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:
```
TCL_FOUND = Tcl was found
TK_FOUND = Tk was found
TCLTK_FOUND = Tcl and Tk were found
TCL_LIBRARY = path to Tcl library (tcl tcl80)
TCL_INCLUDE_PATH = path to where tcl.h can be found
TCL_TCLSH = path to tclsh binary (tcl tcl80)
TK_LIBRARY = path to Tk library (tk tk80 etc)
TK_INCLUDE_PATH = path to where tk.h can be found
TK_WISH = full path to the wish executable
```
In an effort to remove some clutter and clear up some issues for people who are not necessarily Tcl/Tk gurus/developpers, some variables were moved or removed. Changes compared to CMake 2.4 are:
```
=> they were only useful for people writing Tcl/Tk extensions.
=> these libs are not packaged by default with Tcl/Tk distributions.
Even when Tcl/Tk is built from source, several flavors of debug libs
are created and there is no real reason to pick a single one
specifically (say, amongst tcl84g, tcl84gs, or tcl84sgx).
Let's leave that choice to the user by allowing him to assign
TCL_LIBRARY to any Tcl library, debug or not.
=> this ended up being only a Win32 variable, and there is a lot of
confusion regarding the location of this file in an installed Tcl/Tk
tree anyway (see 8.5 for example). If you need the internal path at
this point it is safer you ask directly where the *source* tree is
and dig from there.
```
cmake CPackCygwin CPackCygwin
===========
Cygwin CPack generator (Cygwin).
Variables specific to CPack Cygwin generator
--------------------------------------------
The following variable is specific to installers build on and/or for Cygwin:
`CPACK_CYGWIN_PATCH_NUMBER`
The Cygwin patch number. FIXME: This documentation is incomplete.
`CPACK_CYGWIN_PATCH_FILE`
The Cygwin patch file. FIXME: This documentation is incomplete.
`CPACK_CYGWIN_BUILD_SCRIPT`
The Cygwin build script. FIXME: This documentation is incomplete.
cmake CheckSymbolExists CheckSymbolExists
=================
Provides a macro to check if a symbol exists as a function, variable, or macro in `C`.
`check_symbol_exists`
```
check_symbol_exists(<symbol> <files> <variable>)
```
Check that the `<symbol>` is available after including given header `<files>` and store the result in a `<variable>`. Specify the list of files in one argument as a semicolon-separated list. `<variable>` will be created as an internal cache variable.
If the header files define the symbol as a macro it is considered available and assumed to work. If the header files declare the symbol as a function or variable then the symbol must also be available for linking (so intrinsics may not be detected). If the symbol is a type, enum value, or intrinsic it will not be recognized (consider using [`CheckTypeSize`](checktypesize#module:CheckTypeSize "CheckTypeSize") or [`CheckCSourceCompiles`](checkcsourcecompiles#module:CheckCSourceCompiles "CheckCSourceCompiles")). If the check needs to be done in C++, consider using [`CheckCXXSymbolExists`](checkcxxsymbolexists#module:CheckCXXSymbolExists "CheckCXXSymbolExists") instead.
The following variables may be set before calling this macro to modify the way the check is run:
`CMAKE_REQUIRED_FLAGS` string of compile command line flags
`CMAKE_REQUIRED_DEFINITIONS` list of macros to define (-DFOO=bar)
`CMAKE_REQUIRED_INCLUDES` list of include directories
`CMAKE_REQUIRED_LIBRARIES` list of libraries to link
`CMAKE_REQUIRED_QUIET` execute quietly without messages
cmake FindosgUtil FindosgUtil
===========
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgUtil This module defines
OSGUTIL\_FOUND - Was osgUtil found? OSGUTIL\_INCLUDE\_DIR - Where to find the headers OSGUTIL\_LIBRARIES - The libraries to link for osgUtil (use this)
OSGUTIL\_LIBRARY - The osgUtil library OSGUTIL\_LIBRARY\_DEBUG - The osgUtil debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake AddFileDependencies AddFileDependencies
===================
ADD\_FILE\_DEPENDENCIES(source\_file depend\_files…)
Adds the given files as dependencies to source\_file
cmake FindRTI FindRTI
=======
Try to find M&S HLA RTI libraries
This module finds if any HLA RTI is installed and locates the standard RTI include files and libraries.
RTI is a simulation infrastructure standardized by IEEE and SISO. It has a well defined C++ API that assures that simulation applications are independent on a particular RTI implementation.
```
http://en.wikipedia.org/wiki/Run-Time_Infrastructure_(simulation)
```
This code sets the following variables:
```
RTI_INCLUDE_DIR = the directory where RTI includes file are found
RTI_LIBRARIES = The libraries to link against to use RTI
RTI_DEFINITIONS = -DRTI_USES_STD_FSTREAM
RTI_FOUND = Set to FALSE if any HLA RTI was not found
```
Report problems to <[[email protected]](mailto:certi-devel%40nongnu.org)>
cmake FindRuby FindRuby
========
Find Ruby
This module finds if Ruby is installed and determines where the include files and libraries are. Ruby 1.8, 1.9, 2.0 and 2.1 are supported.
The minimum required version of Ruby can be specified using the standard syntax, e.g. find\_package(Ruby 1.8)
It also determines what the name of the library is. This code sets the following variables:
`RUBY_EXECUTABLE` full path to the ruby binary
`RUBY_INCLUDE_DIRS` include dirs to be used when using the ruby library
`RUBY_LIBRARY` full path to the ruby library
`RUBY_VERSION` the version of ruby which was found, e.g. “1.8.7”
`RUBY_FOUND` set to true if ruby ws found successfully Also:
`RUBY_INCLUDE_PATH` same as RUBY\_INCLUDE\_DIRS, only provided for compatibility reasons, don’t use it
cmake FindMFC FindMFC
=======
Find MFC on Windows
Find the native MFC - i.e. decide if an application can link to the MFC libraries.
```
MFC_FOUND - Was MFC support found
```
You don’t need to include anything or link anything to use it.
cmake FindProtobuf FindProtobuf
============
Locate and configure the Google Protocol Buffers library.
The following variables can be set and are optional:
`Protobuf_SRC_ROOT_FOLDER` When compiling with MSVC, if this cache variable is set the protobuf-default VS project build locations (vsprojects/Debug and vsprojects/Release or vsprojects/x64/Debug and vsprojects/x64/Release) will be searched for libraries and binaries.
`Protobuf_IMPORT_DIRS` List of additional directories to be searched for imported .proto files.
`Protobuf_DEBUG` Show debug messages.
`Protobuf_USE_STATIC_LIBS` Set to ON to force the use of the static libraries. Default is OFF. Defines the following variables:
`Protobuf_FOUND` Found the Google Protocol Buffers library (libprotobuf & header files)
`Protobuf_VERSION` Version of package found.
`Protobuf_INCLUDE_DIRS` Include directories for Google Protocol Buffers
`Protobuf_LIBRARIES` The protobuf libraries
`Protobuf_PROTOC_LIBRARIES` The protoc libraries
`Protobuf_LITE_LIBRARIES` The protobuf-lite libraries The following [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets are also defined:
`protobuf::libprotobuf` The protobuf library.
`protobuf::libprotobuf-lite` The protobuf lite library.
`protobuf::libprotoc` The protoc library. The following cache variables are also available to set or use:
`Protobuf_LIBRARY` The protobuf library
`Protobuf_PROTOC_LIBRARY` The protoc library
`Protobuf_INCLUDE_DIR` The include directory for protocol buffers
`Protobuf_PROTOC_EXECUTABLE` The protoc compiler
`Protobuf_LIBRARY_DEBUG` The protobuf library (debug)
`Protobuf_PROTOC_LIBRARY_DEBUG` The protoc library (debug)
`Protobuf_LITE_LIBRARY` The protobuf lite library
`Protobuf_LITE_LIBRARY_DEBUG` The protobuf lite library (debug) Example:
```
find_package(Protobuf REQUIRED)
include_directories(${Protobuf_INCLUDE_DIRS})
include_directories(${CMAKE_CURRENT_BINARY_DIR})
protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS foo.proto)
protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS EXPORT_MACRO DLL_EXPORT foo.proto)
protobuf_generate_python(PROTO_PY foo.proto)
add_executable(bar bar.cc ${PROTO_SRCS} ${PROTO_HDRS})
target_link_libraries(bar ${Protobuf_LIBRARIES})
```
Note
The `protobuf_generate_cpp` and `protobuf_generate_python` functions and [`add_executable()`](../command/add_executable#command:add_executable "add_executable") or [`add_library()`](../command/add_library#command:add_library "add_library") calls only work properly within the same directory.
`protobuf_generate_cpp`
Add custom commands to process `.proto` files to C++:
```
protobuf_generate_cpp (<SRCS> <HDRS> [EXPORT_MACRO <MACRO>] [<ARGN>...])
```
`SRCS` Variable to define with autogenerated source files
`HDRS` Variable to define with autogenerated header files
`EXPORT_MACRO` is a macro which should expand to `__declspec(dllexport)` or `__declspec(dllimport)` depending on what is being compiled.
`ARGN`
`.proto` files
`protobuf_generate_python`
Add custom commands to process `.proto` files to Python:
```
protobuf_generate_python (<PY> [<ARGN>...])
```
`PY` Variable to define with autogenerated Python files
`ARGN`
`.proto` filess
cmake TestForSSTREAM TestForSSTREAM
==============
Test for compiler support of ANSI sstream header
check if the compiler supports the standard ANSI sstream header
```
CMAKE_NO_ANSI_STRING_STREAM - defined by the results
```
cmake CMakePrintSystemInformation CMakePrintSystemInformation
===========================
print system information
This file can be used for diagnostic purposes just include it in a project to see various internal CMake variables.
cmake FindCups FindCups
========
Try to find the Cups printing system
Once done this will define
```
CUPS_FOUND - system has Cups
CUPS_INCLUDE_DIR - the Cups include directory
CUPS_LIBRARIES - Libraries needed to use Cups
CUPS_VERSION_STRING - version of Cups found (since CMake 2.8.8)
Set CUPS_REQUIRE_IPP_DELETE_ATTRIBUTE to TRUE if you need a version which
features this function (i.e. at least 1.1.19)
```
cmake GNUInstallDirs GNUInstallDirs
==============
Define GNU standard installation directories
Provides install directory variables as defined by the [GNU Coding Standards](https://www.gnu.org/prep/standards/html_node/Directory-Variables.html).
Result Variables
----------------
Inclusion of this module defines the following variables:
`CMAKE_INSTALL_<dir>`
Destination for files of a given type. This value may be passed to the `DESTINATION` options of [`install()`](../command/install#command:install "install") commands for the corresponding file type. `CMAKE_INSTALL_FULL_<dir>`
The absolute path generated from the corresponding `CMAKE_INSTALL_<dir>` value. If the value is not already an absolute path, an absolute path is constructed typically by prepending the value of the [`CMAKE_INSTALL_PREFIX`](../variable/cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") variable. However, there are some [special cases](#special-cases) as documented below. where `<dir>` is one of:
`BINDIR` user executables (`bin`)
`SBINDIR` system admin executables (`sbin`)
`LIBEXECDIR` program executables (`libexec`)
`SYSCONFDIR` read-only single-machine data (`etc`)
`SHAREDSTATEDIR` modifiable architecture-independent data (`com`)
`LOCALSTATEDIR` modifiable single-machine data (`var`)
`RUNSTATEDIR` run-time variable data (`LOCALSTATEDIR/run`)
`LIBDIR` object code libraries (`lib` or `lib64` or `lib/<multiarch-tuple>` on Debian)
`INCLUDEDIR` C header files (`include`)
`OLDINCLUDEDIR` C header files for non-gcc (`/usr/include`)
`DATAROOTDIR` read-only architecture-independent data root (`share`)
`DATADIR` read-only architecture-independent data (`DATAROOTDIR`)
`INFODIR` info documentation (`DATAROOTDIR/info`)
`LOCALEDIR` locale-dependent data (`DATAROOTDIR/locale`)
`MANDIR` man documentation (`DATAROOTDIR/man`)
`DOCDIR` documentation root (`DATAROOTDIR/doc/PROJECT_NAME`) If the includer does not define a value the above-shown default will be used and the value will appear in the cache for editing by the user.
Special Cases
-------------
The following values of [`CMAKE_INSTALL_PREFIX`](../variable/cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") are special:
`/`
For `<dir>` other than the `SYSCONFDIR`, `LOCALSTATEDIR` and `RUNSTATEDIR`, the value of `CMAKE_INSTALL_<dir>` is prefixed with `usr/` if it is not user-specified as an absolute path. For example, the `INCLUDEDIR` value `include` becomes `usr/include`. This is required by the [GNU Coding Standards](https://www.gnu.org/prep/standards/html_node/Directory-Variables.html), which state:
When building the complete GNU system, the prefix will be empty and `/usr` will be a symbolic link to `/`. `/usr`
For `<dir>` equal to `SYSCONFDIR`, `LOCALSTATEDIR` or `RUNSTATEDIR`, the `CMAKE_INSTALL_FULL_<dir>` is computed by prepending just `/` to the value of `CMAKE_INSTALL_<dir>` if it is not user-specified as an absolute path. For example, the `SYSCONFDIR` value `etc` becomes `/etc`. This is required by the [GNU Coding Standards](https://www.gnu.org/prep/standards/html_node/Directory-Variables.html). `/opt/...`
For `<dir>` equal to `SYSCONFDIR`, `LOCALSTATEDIR` or `RUNSTATEDIR`, the `CMAKE_INSTALL_FULL_<dir>` is computed by *appending* the prefix to the value of `CMAKE_INSTALL_<dir>` if it is not user-specified as an absolute path. For example, the `SYSCONFDIR` value `etc` becomes `/etc/opt/...`. This is defined by the [Filesystem Hierarchy Standard](https://refspecs.linuxfoundation.org/FHS_3.0/fhs/index.html). Macros
------
`GNUInstallDirs_get_absolute_install_dir`
```
GNUInstallDirs_get_absolute_install_dir(absvar var)
```
Set the given variable `absvar` to the absolute path contained within the variable `var`. This is to allow the computation of an absolute path, accounting for all the special cases documented above. While this macro is used to compute the various `CMAKE_INSTALL_FULL_<dir>` variables, it is exposed publicly to allow users who create additional path variables to also compute absolute paths where necessary, using the same logic.
cmake FindXCTest FindXCTest
==========
Functions to help creating and executing XCTest bundles.
An XCTest bundle is a CFBundle with a special product-type and bundle extension. The Mac Developer Library provides more information in the [Testing with Xcode](http://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/testing_with_xcode/) document.
Module Functions
----------------
`xctest_add_bundle`
The `xctest_add_bundle` function creates a XCTest bundle named <target> which will test the target <testee>. Supported target types for testee are Frameworks and App Bundles:
```
xctest_add_bundle(
<target> # Name of the XCTest bundle
<testee> # Target name of the testee
)
```
`xctest_add_test`
The `xctest_add_test` function adds an XCTest bundle to the project to be run by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"). The test will be named <name> and tests <bundle>:
```
xctest_add_test(
<name> # Test name
<bundle> # Target name of XCTest bundle
)
```
Module Variables
----------------
The following variables are set by including this module:
`XCTest_FOUND`
True if the XCTest Framework and executable were found.
`XCTest_EXECUTABLE`
The path to the xctest command line tool used to execute XCTest bundles.
`XCTest_INCLUDE_DIRS`
The directory containing the XCTest Framework headers.
`XCTest_LIBRARIES`
The location of the XCTest Framework.
cmake CheckVariableExists CheckVariableExists
===================
Check if the variable exists.
```
CHECK_VARIABLE_EXISTS(VAR VARIABLE)
```
```
VAR - the name of the variable
VARIABLE - variable to store the result
Will be created as an internal cache variable.
```
This macro is only for C variables.
The following variables may be set before calling this macro to modify the way the check is run:
```
CMAKE_REQUIRED_FLAGS = string of compile command line flags
CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
CMAKE_REQUIRED_QUIET = execute quietly without messages
```
| programming_docs |
cmake BundleUtilities BundleUtilities
===============
Functions to help assemble a standalone bundle application.
A collection of CMake utility functions useful for dealing with .app bundles on the Mac and bundle-like directories on any OS.
The following functions are provided by this module:
```
fixup_bundle
copy_and_fixup_bundle
verify_app
get_bundle_main_executable
get_dotapp_dir
get_bundle_and_executable
get_bundle_all_executables
get_item_key
get_item_rpaths
clear_bundle_keys
set_bundle_key_values
get_bundle_keys
copy_resolved_item_into_bundle
copy_resolved_framework_into_bundle
fixup_bundle_item
verify_bundle_prerequisites
verify_bundle_symlinks
```
Requires CMake 2.6 or greater because it uses function, break and PARENT\_SCOPE. Also depends on GetPrerequisites.cmake.
```
FIXUP_BUNDLE(<app> <libs> <dirs>)
```
Fix up a bundle in-place and make it standalone, such that it can be drag-n-drop copied to another machine and run on that machine as long as all of the system libraries are compatible.
If you pass plugins to fixup\_bundle as the libs parameter, you should install them or copy them into the bundle before calling fixup\_bundle. The “libs” parameter is a list of libraries that must be fixed up, but that cannot be determined by otool output analysis. (i.e., plugins)
Gather all the keys for all the executables and libraries in a bundle, and then, for each key, copy each prerequisite into the bundle. Then fix each one up according to its own list of prerequisites.
Then clear all the keys and call verify\_app on the final bundle to ensure that it is truly standalone.
As an optional parameter (IGNORE\_ITEM) a list of file names can be passed, which are then ignored (e.g. IGNORE\_ITEM “vcredist\_x86.exe;vcredist\_x64.exe”)
```
COPY_AND_FIXUP_BUNDLE(<src> <dst> <libs> <dirs>)
```
Makes a copy of the bundle <src> at location <dst> and then fixes up the new copied bundle in-place at <dst>…
```
VERIFY_APP(<app>)
```
Verifies that an application <app> appears valid based on running analysis tools on it. Calls “message(FATAL\_ERROR” if the application is not verified.
As an optional parameter (IGNORE\_ITEM) a list of file names can be passed, which are then ignored (e.g. IGNORE\_ITEM “vcredist\_x86.exe;vcredist\_x64.exe”)
```
GET_BUNDLE_MAIN_EXECUTABLE(<bundle> <result_var>)
```
The result will be the full path name of the bundle’s main executable file or an “error:” prefixed string if it could not be determined.
```
GET_DOTAPP_DIR(<exe> <dotapp_dir_var>)
```
Returns the nearest parent dir whose name ends with “.app” given the full path to an executable. If there is no such parent dir, then simply return the dir containing the executable.
The returned directory may or may not exist.
```
GET_BUNDLE_AND_EXECUTABLE(<app> <bundle_var> <executable_var> <valid_var>)
```
Takes either a “.app” directory name or the name of an executable nested inside a “.app” directory and returns the path to the “.app” directory in <bundle\_var> and the path to its main executable in <executable\_var>
```
GET_BUNDLE_ALL_EXECUTABLES(<bundle> <exes_var>)
```
Scans the given bundle recursively for all executable files and accumulates them into a variable.
```
GET_ITEM_KEY(<item> <key_var>)
```
Given a file (item) name, generate a key that should be unique considering the set of libraries that need copying or fixing up to make a bundle standalone. This is essentially the file name including extension with “.” replaced by “\_”
This key is used as a prefix for CMake variables so that we can associate a set of variables with a given item based on its key.
```
CLEAR_BUNDLE_KEYS(<keys_var>)
```
Loop over the list of keys, clearing all the variables associated with each key. After the loop, clear the list of keys itself.
Caller of get\_bundle\_keys should call clear\_bundle\_keys when done with list of keys.
```
SET_BUNDLE_KEY_VALUES(<keys_var> <context> <item> <exepath> <dirs>
<copyflag> [<rpaths>])
```
Add a key to the list (if necessary) for the given item. If added, also set all the variables associated with that key.
```
GET_BUNDLE_KEYS(<app> <libs> <dirs> <keys_var>)
```
Loop over all the executable and library files within the bundle (and given as extra <libs>) and accumulate a list of keys representing them. Set values associated with each key such that we can loop over all of them and copy prerequisite libs into the bundle and then do appropriate install\_name\_tool fixups.
As an optional parameter (IGNORE\_ITEM) a list of file names can be passed, which are then ignored (e.g. IGNORE\_ITEM “vcredist\_x86.exe;vcredist\_x64.exe”)
```
COPY_RESOLVED_ITEM_INTO_BUNDLE(<resolved_item> <resolved_embedded_item>)
```
Copy a resolved item into the bundle if necessary. Copy is not necessary if the resolved\_item is “the same as” the resolved\_embedded\_item.
```
COPY_RESOLVED_FRAMEWORK_INTO_BUNDLE(<resolved_item> <resolved_embedded_item>)
```
Copy a resolved framework into the bundle if necessary. Copy is not necessary if the resolved\_item is “the same as” the resolved\_embedded\_item.
By default, BU\_COPY\_FULL\_FRAMEWORK\_CONTENTS is not set. If you want full frameworks embedded in your bundles, set BU\_COPY\_FULL\_FRAMEWORK\_CONTENTS to ON before calling fixup\_bundle. By default, COPY\_RESOLVED\_FRAMEWORK\_INTO\_BUNDLE copies the framework dylib itself plus the framework Resources directory.
```
FIXUP_BUNDLE_ITEM(<resolved_embedded_item> <exepath> <dirs>)
```
Get the direct/non-system prerequisites of the resolved embedded item. For each prerequisite, change the way it is referenced to the value of the \_EMBEDDED\_ITEM keyed variable for that prerequisite. (Most likely changing to an “@executable\_path” style reference.)
This function requires that the resolved\_embedded\_item be “inside” the bundle already. In other words, if you pass plugins to fixup\_bundle as the libs parameter, you should install them or copy them into the bundle before calling fixup\_bundle. The “libs” parameter is a list of libraries that must be fixed up, but that cannot be determined by otool output analysis. (i.e., plugins)
Also, change the id of the item being fixed up to its own \_EMBEDDED\_ITEM value.
Accumulate changes in a local variable and make *one* call to install\_name\_tool at the end of the function with all the changes at once.
If the BU\_CHMOD\_BUNDLE\_ITEMS variable is set then bundle items will be marked writable before install\_name\_tool tries to change them.
```
VERIFY_BUNDLE_PREREQUISITES(<bundle> <result_var> <info_var>)
```
Verifies that the sum of all prerequisites of all files inside the bundle are contained within the bundle or are “system” libraries, presumed to exist everywhere.
As an optional parameter (IGNORE\_ITEM) a list of file names can be passed, which are then ignored (e.g. IGNORE\_ITEM “vcredist\_x86.exe;vcredist\_x64.exe”)
```
VERIFY_BUNDLE_SYMLINKS(<bundle> <result_var> <info_var>)
```
Verifies that any symlinks found in the bundle point to other files that are already also in the bundle… Anything that points to an external file causes this function to fail the verification.
cmake FindPackageMessage FindPackageMessage
==================
FIND\_PACKAGE\_MESSAGE(<name> “message for user” “find result details”)
This macro is intended to be used in FindXXX.cmake modules files. It will print a message once for each unique find result. This is useful for telling the user where a package was found. The first argument specifies the name (XXX) of the package. The second argument specifies the message to display. The third argument lists details about the find result so that if they change the message will be displayed again. The macro also obeys the QUIET argument to the find\_package command.
Example:
```
if(X11_FOUND)
FIND_PACKAGE_MESSAGE(X11 "Found X11: ${X11_X11_LIB}"
"[${X11_X11_LIB}][${X11_INCLUDE_DIR}]")
else()
...
endif()
```
cmake FindZLIB FindZLIB
========
Find the native ZLIB includes and library.
IMPORTED Targets
----------------
This module defines [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target `ZLIB::ZLIB`, if ZLIB has been found.
Result Variables
----------------
This module defines the following variables:
```
ZLIB_INCLUDE_DIRS - where to find zlib.h, etc.
ZLIB_LIBRARIES - List of libraries when using zlib.
ZLIB_FOUND - True if zlib found.
```
```
ZLIB_VERSION_STRING - The version of zlib found (x.y.z)
ZLIB_VERSION_MAJOR - The major version of zlib
ZLIB_VERSION_MINOR - The minor version of zlib
ZLIB_VERSION_PATCH - The patch version of zlib
ZLIB_VERSION_TWEAK - The tweak version of zlib
```
Backward Compatibility
----------------------
The following variable are provided for backward compatibility
```
ZLIB_MAJOR_VERSION - The major version of zlib
ZLIB_MINOR_VERSION - The minor version of zlib
ZLIB_PATCH_VERSION - The patch version of zlib
```
Hints
-----
A user may set `ZLIB_ROOT` to a zlib installation root to tell this module where to look.
cmake FindFLEX FindFLEX
========
Find flex executable and provides a macro to generate custom build rules
The module defines the following variables:
```
FLEX_FOUND - true is flex executable is found
FLEX_EXECUTABLE - the path to the flex executable
FLEX_VERSION - the version of flex
FLEX_LIBRARIES - The flex libraries
FLEX_INCLUDE_DIRS - The path to the flex headers
```
The minimum required version of flex can be specified using the standard syntax, e.g. find\_package(FLEX 2.5.13)
If flex is found on the system, the module provides the macro:
```
FLEX_TARGET(Name FlexInput FlexOutput
[COMPILE_FLAGS <string>]
[DEFINES_FILE <string>]
)
```
which creates a custom command to generate the <FlexOutput> file from the <FlexInput> file. If COMPILE\_FLAGS option is specified, the next parameter is added to the flex command line. If flex is configured to output a header file, the DEFINES\_FILE option may be used to specify its name. Name is an alias used to get details of this custom command. Indeed the macro defines the following variables:
```
FLEX_${Name}_DEFINED - true is the macro ran successfully
FLEX_${Name}_OUTPUTS - the source file generated by the custom rule, an
alias for FlexOutput
FLEX_${Name}_INPUT - the flex source file, an alias for ${FlexInput}
FLEX_${Name}_OUTPUT_HEADER - the header flex output, if any.
```
Flex scanners oftenly use tokens defined by Bison: the code generated by Flex depends of the header generated by Bison. This module also defines a macro:
```
ADD_FLEX_BISON_DEPENDENCY(FlexTarget BisonTarget)
```
which adds the required dependency between a scanner and a parser where <FlexTarget> and <BisonTarget> are the first parameters of respectively FLEX\_TARGET and BISON\_TARGET macros.
```
====================================================================
Example:
```
```
find_package(BISON)
find_package(FLEX)
```
```
BISON_TARGET(MyParser parser.y ${CMAKE_CURRENT_BINARY_DIR}/parser.cpp)
FLEX_TARGET(MyScanner lexer.l ${CMAKE_CURRENT_BINARY_DIR}/lexer.cpp)
ADD_FLEX_BISON_DEPENDENCY(MyScanner MyParser)
```
```
include_directories(${CMAKE_CURRENT_BINARY_DIR})
add_executable(Foo
Foo.cc
${BISON_MyParser_OUTPUTS}
${FLEX_MyScanner_OUTPUTS}
)
====================================================================
```
cmake CheckCXXSourceRuns CheckCXXSourceRuns
==================
Check if the given C++ source code compiles and runs.
CHECK\_CXX\_SOURCE\_RUNS(<code> <var>)
```
<code> - source code to try to compile
<var> - variable to store the result
(1 for success, empty for failure)
Will be created as an internal cache variable.
```
The following variables may be set before calling this macro to modify the way the check is run:
```
CMAKE_REQUIRED_FLAGS = string of compile command line flags
CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
CMAKE_REQUIRED_INCLUDES = list of include directories
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
CMAKE_REQUIRED_QUIET = execute quietly without messages
```
cmake CMakeDependentOption CMakeDependentOption
====================
Macro to provide an option dependent on other options.
This macro presents an option to the user only if a set of other conditions are true. When the option is not presented a default value is used, but any value set by the user is preserved for when the option is presented again. Example invocation:
```
CMAKE_DEPENDENT_OPTION(USE_FOO "Use Foo" ON
"USE_BAR;NOT USE_ZOT" OFF)
```
If USE\_BAR is true and USE\_ZOT is false, this provides an option called USE\_FOO that defaults to ON. Otherwise, it sets USE\_FOO to OFF. If the status of USE\_BAR or USE\_ZOT ever changes, any value for the USE\_FOO option is saved so that when the option is re-enabled it retains its old value.
cmake CheckPrototypeDefinition CheckPrototypeDefinition
========================
Check if the protoype we expect is correct.
check\_prototype\_definition(FUNCTION PROTOTYPE RETURN HEADER VARIABLE)
```
FUNCTION - The name of the function (used to check if prototype exists)
PROTOTYPE- The prototype to check.
RETURN - The return value of the function.
HEADER - The header files required.
VARIABLE - The variable to store the result.
Will be created as an internal cache variable.
```
Example:
```
check_prototype_definition(getpwent_r
"struct passwd *getpwent_r(struct passwd *src, char *buf, int buflen)"
"NULL"
"unistd.h;pwd.h"
SOLARIS_GETPWENT_R)
```
The following variables may be set before calling this macro to modify the way the check is run:
```
CMAKE_REQUIRED_FLAGS = string of compile command line flags
CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
CMAKE_REQUIRED_INCLUDES = list of include directories
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
CMAKE_REQUIRED_QUIET = execute quietly without messages
```
cmake CMakePushCheckState CMakePushCheckState
===================
This module defines three macros: CMAKE\_PUSH\_CHECK\_STATE() CMAKE\_POP\_CHECK\_STATE() and CMAKE\_RESET\_CHECK\_STATE() These macros can be used to save, restore and reset (i.e., clear contents) the state of the variables CMAKE\_REQUIRED\_FLAGS, CMAKE\_REQUIRED\_DEFINITIONS, CMAKE\_REQUIRED\_LIBRARIES, CMAKE\_REQUIRED\_INCLUDES and CMAKE\_EXTRA\_INCLUDE\_FILES used by the various Check-files coming with CMake, like e.g. check\_function\_exists() etc. The variable contents are pushed on a stack, pushing multiple times is supported. This is useful e.g. when executing such tests in a Find-module, where they have to be set, but after the Find-module has been executed they should have the same value as they had before.
CMAKE\_PUSH\_CHECK\_STATE() macro receives optional argument RESET. Whether it’s specified, CMAKE\_PUSH\_CHECK\_STATE() will set all CMAKE\_REQUIRED\_\* variables to empty values, same as CMAKE\_RESET\_CHECK\_STATE() call will do.
Usage:
```
cmake_push_check_state(RESET)
set(CMAKE_REQUIRED_DEFINITIONS -DSOME_MORE_DEF)
check_function_exists(...)
cmake_reset_check_state()
set(CMAKE_REQUIRED_DEFINITIONS -DANOTHER_DEF)
check_function_exists(...)
cmake_pop_check_state()
```
cmake Use_wxWindows Use\_wxWindows
==============
This convenience include finds if wxWindows is installed and set the appropriate libs, incdirs, flags etc. author Jan Woetzel <jw -at- mip.informatik.uni-kiel.de> (07/2003)
USAGE:
```
just include Use_wxWindows.cmake
in your projects CMakeLists.txt
```
include( ${CMAKE\_MODULE\_PATH}/Use\_wxWindows.cmake)
```
if you are sure you need GL then
```
set(WXWINDOWS\_USE\_GL 1)
```
*before* you include this file.
```
cmake SquishTestScript SquishTestScript
================
This script launches a GUI test using Squish. You should not call the script directly; instead, you should access it via the SQUISH\_ADD\_TEST macro that is defined in FindSquish.cmake.
This script starts the Squish server, launches the test on the client, and finally stops the squish server. If any of these steps fail (including if the tests do not pass) then a fatal error is raised.
cmake FindosgShadow FindosgShadow
=============
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgShadow This module defines
OSGSHADOW\_FOUND - Was osgShadow found? OSGSHADOW\_INCLUDE\_DIR - Where to find the headers OSGSHADOW\_LIBRARIES - The libraries to link for osgShadow (use this)
OSGSHADOW\_LIBRARY - The osgShadow library OSGSHADOW\_LIBRARY\_DEBUG - The osgShadow debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake FindDevIL FindDevIL
=========
This module locates the developer’s image library. <http://openil.sourceforge.net/>
This module sets:
```
IL_LIBRARIES - the name of the IL library. These include the full path to
the core DevIL library. This one has to be linked into the
application.
ILU_LIBRARIES - the name of the ILU library. Again, the full path. This
library is for filters and effects, not actual loading. It
doesn't have to be linked if the functionality it provides
is not used.
ILUT_LIBRARIES - the name of the ILUT library. Full path. This part of the
library interfaces with OpenGL. It is not strictly needed
in applications.
IL_INCLUDE_DIR - where to find the il.h, ilu.h and ilut.h files.
DevIL_FOUND - this is set to TRUE if all the above variables were set.
This will be set to false if ILU or ILUT are not found,
even if they are not needed. In most systems, if one
library is found all the others are as well. That's the
way the DevIL developers release it.
```
cmake CheckFortranCompilerFlag CheckFortranCompilerFlag
========================
Check whether the Fortran compiler supports a given flag.
CHECK\_Fortran\_COMPILER\_FLAG(<flag> <var>)
```
<flag> - the compiler flag
<var> - variable to store the result
Will be created as an internal cache variable.
```
This internally calls the check\_fortran\_source\_compiles macro and sets CMAKE\_REQUIRED\_DEFINITIONS to <flag>. See help for CheckFortranSourceCompiles for a listing of variables that can otherwise modify the build. The result only tells that the compiler does not give an error message when it encounters the flag. If the flag has any effect or even a specific one is beyond the scope of this module.
cmake FindSquish FindSquish
==========
– Typical Use
This module can be used to find Squish. Currently Squish versions 3 and 4 are supported.
```
SQUISH_FOUND If false, don't try to use Squish
SQUISH_VERSION The full version of Squish found
SQUISH_VERSION_MAJOR The major version of Squish found
SQUISH_VERSION_MINOR The minor version of Squish found
SQUISH_VERSION_PATCH The patch version of Squish found
```
```
SQUISH_INSTALL_DIR The Squish installation directory
(containing bin, lib, etc)
SQUISH_SERVER_EXECUTABLE The squishserver executable
SQUISH_CLIENT_EXECUTABLE The squishrunner executable
```
```
SQUISH_INSTALL_DIR_FOUND Was the install directory found?
SQUISH_SERVER_EXECUTABLE_FOUND Was the server executable found?
SQUISH_CLIENT_EXECUTABLE_FOUND Was the client executable found?
```
It provides the function squish\_v4\_add\_test() for adding a squish test to cmake using Squish 4.x:
```
squish_v4_add_test(cmakeTestName
AUT targetName SUITE suiteName TEST squishTestName
[SETTINGSGROUP group] [PRE_COMMAND command] [POST_COMMAND command] )
```
The arguments have the following meaning:
`cmakeTestName` this will be used as the first argument for add\_test()
`AUT targetName` the name of the cmake target which will be used as AUT, i.e. the executable which will be tested.
`SUITE suiteName` this is either the full path to the squish suite, or just the last directory of the suite, i.e. the suite name. In this case the CMakeLists.txt which calls squish\_add\_test() must be located in the parent directory of the suite directory.
`TEST squishTestName` the name of the squish test, i.e. the name of the subdirectory of the test inside the suite directory.
`SETTINGSGROUP group` if specified, the given settings group will be used for executing the test. If not specified, the groupname will be “CTest\_<username>”
`PRE_COMMAND command` if specified, the given command will be executed before starting the squish test.
`POST_COMMAND command` same as PRE\_COMMAND, but after the squish test has been executed.
```
enable_testing()
find_package(Squish 4.0)
if (SQUISH_FOUND)
squish_v4_add_test(myTestName
AUT myApp
SUITE ${CMAKE_SOURCE_DIR}/tests/mySuite
TEST someSquishTest
SETTINGSGROUP myGroup
)
endif ()
```
For users of Squish version 3.x the macro squish\_v3\_add\_test() is provided:
```
squish_v3_add_test(testName applicationUnderTest testCase envVars testWrapper)
Use this macro to add a test using Squish 3.x.
```
```
enable_testing()
find_package(Squish)
if (SQUISH_FOUND)
squish_v3_add_test(myTestName myApplication testCase envVars testWrapper)
endif ()
```
macro SQUISH\_ADD\_TEST(testName applicationUnderTest testCase envVars testWrapper)
```
This is deprecated. Use SQUISH_V3_ADD_TEST() if you are using Squish 3.x instead.
```
| programming_docs |
cmake CMakeGraphVizOptions CMakeGraphVizOptions
====================
The builtin graphviz support of CMake.
Variables specific to the graphviz support
------------------------------------------
CMake can generate graphviz files, showing the dependencies between the targets in a project and also external libraries which are linked against. When CMake is run with the –graphviz=foo.dot option, it will produce:
* a foo.dot file showing all dependencies in the project
* a foo.dot.<target> file for each target, file showing on which other targets the respective target depends
* a foo.dot.<target>.dependers file, showing which other targets depend on the respective target
This can result in huge graphs. Using the file CMakeGraphVizOptions.cmake the look and content of the generated graphs can be influenced. This file is searched first in ${CMAKE\_BINARY\_DIR} and then in ${CMAKE\_SOURCE\_DIR}. If found, it is read and the variables set in it are used to adjust options for the generated graphviz files.
`GRAPHVIZ_GRAPH_TYPE`
The graph type.
* Mandatory : NO
* Default : “digraph”
Valid graph types are:
* “graph” : Nodes are joined with lines
* “digraph” : Nodes are joined with arrows showing direction
* “strict graph” : Like “graph” but max one line between each node
* “strict digraph” : Like “graph” but max one line between each node in each direction
`GRAPHVIZ_GRAPH_NAME`
The graph name.
* Mandatory : NO
* Default : “GG”
`GRAPHVIZ_GRAPH_HEADER`
The header written at the top of the graphviz file.
* Mandatory : NO
* Default : “node [n fontsize = “12”];”
`GRAPHVIZ_NODE_PREFIX`
The prefix for each node in the graphviz file.
* Mandatory : NO
* Default : “node”
`GRAPHVIZ_EXECUTABLES`
Set this to FALSE to exclude executables from the generated graphs.
* Mandatory : NO
* Default : TRUE
`GRAPHVIZ_STATIC_LIBS`
Set this to FALSE to exclude static libraries from the generated graphs.
* Mandatory : NO
* Default : TRUE
`GRAPHVIZ_SHARED_LIBS`
Set this to FALSE to exclude shared libraries from the generated graphs.
* Mandatory : NO
* Default : TRUE
`GRAPHVIZ_MODULE_LIBS`
Set this to FALSE to exclude module libraries from the generated graphs.
* Mandatory : NO
* Default : TRUE
`GRAPHVIZ_EXTERNAL_LIBS`
Set this to FALSE to exclude external libraries from the generated graphs.
* Mandatory : NO
* Default : TRUE
`GRAPHVIZ_IGNORE_TARGETS`
A list of regular expressions for ignoring targets.
* Mandatory : NO
* Default : empty
`GRAPHVIZ_GENERATE_PER_TARGET`
Set this to FALSE to exclude per target graphs `foo.dot.<target>`.
* Mandatory : NO
* Default : TRUE
`GRAPHVIZ_GENERATE_DEPENDERS`
Set this to FALSE to exclude depender graphs `foo.dot.<target>.dependers`.
* Mandatory : NO
* Default : TRUE
cmake CMakeAddFortranSubdirectory CMakeAddFortranSubdirectory
===========================
Use MinGW gfortran from VS if a fortran compiler is not found.
The ‘add\_fortran\_subdirectory’ function adds a subdirectory to a project that contains a fortran only sub-project. The module will check the current compiler and see if it can support fortran. If no fortran compiler is found and the compiler is MSVC, then this module will find the MinGW gfortran. It will then use an external project to build with the MinGW tools. It will also create imported targets for the libraries created. This will only work if the fortran code is built into a dll, so BUILD\_SHARED\_LIBS is turned on in the project. In addition the CMAKE\_GNUtoMS option is set to on, so that the MS .lib files are created. Usage is as follows:
```
cmake_add_fortran_subdirectory(
<subdir> # name of subdirectory
PROJECT <project_name> # project name in subdir top CMakeLists.txt
ARCHIVE_DIR <dir> # dir where project places .lib files
RUNTIME_DIR <dir> # dir where project places .dll files
LIBRARIES <lib>... # names of library targets to import
LINK_LIBRARIES # link interface libraries for LIBRARIES
[LINK_LIBS <lib> <dep>...]...
CMAKE_COMMAND_LINE ... # extra command line flags to pass to cmake
NO_EXTERNAL_INSTALL # skip installation of external project
)
```
Relative paths in ARCHIVE\_DIR and RUNTIME\_DIR are interpreted with respect to the build directory corresponding to the source directory in which the function is invoked.
Limitations:
NO\_EXTERNAL\_INSTALL is required for forward compatibility with a future version that supports installation of the external project binaries during “make install”.
cmake FindICU FindICU
=======
Find the International Components for Unicode (ICU) libraries and programs.
This module supports multiple components. Components can include any of: `data`, `i18n`, `io`, `le`, `lx`, `test`, `tu` and `uc`.
Note that on Windows `data` is named `dt` and `i18n` is named `in`; any of the names may be used, and the appropriate platform-specific library name will be automatically selected.
This module reports information about the ICU installation in several variables. General variables:
```
ICU_VERSION - ICU release version
ICU_FOUND - true if the main programs and libraries were found
ICU_LIBRARIES - component libraries to be linked
ICU_INCLUDE_DIRS - the directories containing the ICU headers
```
Imported targets:
```
ICU::<C>
```
Where `<C>` is the name of an ICU component, for example `ICU::i18n`.
ICU programs are reported in:
```
ICU_GENCNVAL_EXECUTABLE - path to gencnval executable
ICU_ICUINFO_EXECUTABLE - path to icuinfo executable
ICU_GENBRK_EXECUTABLE - path to genbrk executable
ICU_ICU-CONFIG_EXECUTABLE - path to icu-config executable
ICU_GENRB_EXECUTABLE - path to genrb executable
ICU_GENDICT_EXECUTABLE - path to gendict executable
ICU_DERB_EXECUTABLE - path to derb executable
ICU_PKGDATA_EXECUTABLE - path to pkgdata executable
ICU_UCONV_EXECUTABLE - path to uconv executable
ICU_GENCFU_EXECUTABLE - path to gencfu executable
ICU_MAKECONV_EXECUTABLE - path to makeconv executable
ICU_GENNORM2_EXECUTABLE - path to gennorm2 executable
ICU_GENCCODE_EXECUTABLE - path to genccode executable
ICU_GENSPREP_EXECUTABLE - path to gensprep executable
ICU_ICUPKG_EXECUTABLE - path to icupkg executable
ICU_GENCMN_EXECUTABLE - path to gencmn executable
```
ICU component libraries are reported in:
```
ICU_<C>_FOUND - ON if component was found
ICU_<C>_LIBRARIES - libraries for component
```
Note that `<C>` is the uppercased name of the component.
This module reads hints about search results from:
```
ICU_ROOT - the root of the ICU installation
```
The environment variable `ICU_ROOT` may also be used; the ICU\_ROOT variable takes precedence.
The following cache variables may also be set:
```
ICU_<P>_EXECUTABLE - the path to executable <P>
ICU_INCLUDE_DIR - the directory containing the ICU headers
ICU_<C>_LIBRARY - the library for component <C>
```
Note
In most cases none of the above variables will require setting, unless multiple ICU versions are available and a specific version is required.
Other variables one may set to control this module are:
```
ICU_DEBUG - Set to ON to enable debug output from FindICU.
```
cmake CheckIPOSupported CheckIPOSupported
=================
Check whether the compiler supports an interprocedural optimization (IPO/LTO). Use this before enabling the [`INTERPROCEDURAL_OPTIMIZATION`](../prop_tgt/interprocedural_optimization#prop_tgt:INTERPROCEDURAL_OPTIMIZATION "INTERPROCEDURAL_OPTIMIZATION") target property.
`check_ipo_supported`
```
check_ipo_supported([RESULT <result>] [OUTPUT <output>]
[LANGUAGES <lang>...])
```
Options are:
`RESULT <result>` Set `<result>` variable to `YES` if IPO is supported by the compiler and `NO` otherwise. If this option is not given then the command will issue a fatal error if IPO is not supported.
`OUTPUT <output>` Set `<output>` variable with details about any error.
`LANGUAGES <lang>...` Specify languages whose compilers to check. Languages `C` and `CXX` are supported.
It makes no sense to use this module when [`CMP0069`](../policy/cmp0069#policy:CMP0069 "CMP0069") is set to `OLD` so module will return error in this case. See policy [`CMP0069`](../policy/cmp0069#policy:CMP0069 "CMP0069") for details.
Examples
--------
```
check_ipo_supported() # fatal error if IPO is not supported
set_property(TARGET foo PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
```
```
# Optional IPO. Do not use IPO if it's not supported by compiler.
check_ipo_supported(RESULT result OUTPUT output)
if(result)
set_property(TARGET foo PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
else()
message(WARNING "IPO is not supported: ${output}")
endif()
```
cmake FindX11 FindX11
=======
Find X11 installation
Try to find X11 on UNIX systems. The following values are defined
```
X11_FOUND - True if X11 is available
X11_INCLUDE_DIR - include directories to use X11
X11_LIBRARIES - link against these to use X11
```
and also the following more fine grained variables:
```
X11_ICE_INCLUDE_PATH, X11_ICE_LIB, X11_ICE_FOUND
X11_SM_INCLUDE_PATH, X11_SM_LIB, X11_SM_FOUND
X11_X11_INCLUDE_PATH, X11_X11_LIB
X11_Xaccessrules_INCLUDE_PATH, X11_Xaccess_FOUND
X11_Xaccessstr_INCLUDE_PATH, X11_Xaccess_FOUND
X11_Xau_INCLUDE_PATH, X11_Xau_LIB, X11_Xau_FOUND
X11_Xcomposite_INCLUDE_PATH, X11_Xcomposite_LIB, X11_Xcomposite_FOUND
X11_Xcursor_INCLUDE_PATH, X11_Xcursor_LIB, X11_Xcursor_FOUND
X11_Xdamage_INCLUDE_PATH, X11_Xdamage_LIB, X11_Xdamage_FOUND
X11_Xdmcp_INCLUDE_PATH, X11_Xdmcp_LIB, X11_Xdmcp_FOUND
X11_Xext_LIB, X11_Xext_FOUND
X11_dpms_INCLUDE_PATH, (in X11_Xext_LIB), X11_dpms_FOUND
X11_XShm_INCLUDE_PATH, (in X11_Xext_LIB), X11_XShm_FOUND
X11_Xshape_INCLUDE_PATH, (in X11_Xext_LIB), X11_Xshape_FOUND
X11_xf86misc_INCLUDE_PATH, X11_Xxf86misc_LIB, X11_xf86misc_FOUND
X11_xf86vmode_INCLUDE_PATH, X11_Xxf86vm_LIB X11_xf86vmode_FOUND
X11_Xfixes_INCLUDE_PATH, X11_Xfixes_LIB, X11_Xfixes_FOUND
X11_Xft_INCLUDE_PATH, X11_Xft_LIB, X11_Xft_FOUND
X11_Xi_INCLUDE_PATH, X11_Xi_LIB, X11_Xi_FOUND
X11_Xinerama_INCLUDE_PATH, X11_Xinerama_LIB, X11_Xinerama_FOUND
X11_Xinput_INCLUDE_PATH, X11_Xinput_LIB, X11_Xinput_FOUND
X11_Xkb_INCLUDE_PATH, X11_Xkb_FOUND
X11_Xkblib_INCLUDE_PATH, X11_Xkb_FOUND
X11_Xkbfile_INCLUDE_PATH, X11_Xkbfile_LIB, X11_Xkbfile_FOUND
X11_Xmu_INCLUDE_PATH, X11_Xmu_LIB, X11_Xmu_FOUND
X11_Xpm_INCLUDE_PATH, X11_Xpm_LIB, X11_Xpm_FOUND
X11_XTest_INCLUDE_PATH, X11_XTest_LIB, X11_XTest_FOUND
X11_Xrandr_INCLUDE_PATH, X11_Xrandr_LIB, X11_Xrandr_FOUND
X11_Xrender_INCLUDE_PATH, X11_Xrender_LIB, X11_Xrender_FOUND
X11_Xscreensaver_INCLUDE_PATH, X11_Xscreensaver_LIB, X11_Xscreensaver_FOUND
X11_Xt_INCLUDE_PATH, X11_Xt_LIB, X11_Xt_FOUND
X11_Xutil_INCLUDE_PATH, X11_Xutil_FOUND
X11_Xv_INCLUDE_PATH, X11_Xv_LIB, X11_Xv_FOUND
X11_XSync_INCLUDE_PATH, (in X11_Xext_LIB), X11_XSync_FOUND
```
cmake FindQt4 FindQt4
=======
Finding and Using Qt4
---------------------
This module can be used to find Qt4. The most important issue is that the Qt4 qmake is available via the system path. This qmake is then used to detect basically everything else. This module defines a number of [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets, macros and variables.
Typical usage could be something like:
```
set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
find_package(Qt4 4.4.3 REQUIRED QtGui QtXml)
add_executable(myexe main.cpp)
target_link_libraries(myexe Qt4::QtGui Qt4::QtXml)
```
Note
When using [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets, the qtmain.lib static library is automatically linked on Windows for [`WIN32`](../prop_tgt/win32_executable#prop_tgt:WIN32_EXECUTABLE "WIN32_EXECUTABLE") executables. To disable that globally, set the `QT4_NO_LINK_QTMAIN` variable before finding Qt4. To disable that for a particular executable, set the `QT4_NO_LINK_QTMAIN` target property to `TRUE` on the executable.
Qt Build Tools
--------------
Qt relies on some bundled tools for code generation, such as `moc` for meta-object code generation,``uic`` for widget layout and population, and `rcc` for virtual filesystem content generation. These tools may be automatically invoked by [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") if the appropriate conditions are met. See [`cmake-qt(7)`](../manual/cmake-qt.7#manual:cmake-qt(7) "cmake-qt(7)") for more.
Qt Macros
---------
In some cases it can be necessary or useful to invoke the Qt build tools in a more-manual way. Several macros are available to add targets for such uses.
```
macro QT4_WRAP_CPP(outfiles inputfile ... [TARGET tgt] OPTIONS ...)
create moc code from a list of files containing Qt class with
the Q_OBJECT declaration. Per-directory preprocessor definitions
are also added. If the <tgt> is specified, the
INTERFACE_INCLUDE_DIRECTORIES and INTERFACE_COMPILE_DEFINITIONS from
the <tgt> are passed to moc. Options may be given to moc, such as
those found when executing "moc -help".
```
```
macro QT4_WRAP_UI(outfiles inputfile ... OPTIONS ...)
create code from a list of Qt designer ui files.
Options may be given to uic, such as those found
when executing "uic -help"
```
```
macro QT4_ADD_RESOURCES(outfiles inputfile ... OPTIONS ...)
create code from a list of Qt resource files.
Options may be given to rcc, such as those found
when executing "rcc -help"
```
```
macro QT4_GENERATE_MOC(inputfile outputfile [TARGET tgt])
creates a rule to run moc on infile and create outfile.
Use this if for some reason QT4_WRAP_CPP() isn't appropriate, e.g.
because you need a custom filename for the moc file or something
similar. If the <tgt> is specified, the
INTERFACE_INCLUDE_DIRECTORIES and INTERFACE_COMPILE_DEFINITIONS from
the <tgt> are passed to moc.
```
```
macro QT4_ADD_DBUS_INTERFACE(outfiles interface basename)
Create the interface header and implementation files with the
given basename from the given interface xml file and add it to
the list of sources.
You can pass additional parameters to the qdbusxml2cpp call by setting
properties on the input file:
INCLUDE the given file will be included in the generate interface header
CLASSNAME the generated class is named accordingly
NO_NAMESPACE the generated class is not wrapped in a namespace
```
```
macro QT4_ADD_DBUS_INTERFACES(outfiles inputfile ... )
Create the interface header and implementation files
for all listed interface xml files.
The basename will be automatically determined from the name
of the xml file.
The source file properties described for
QT4_ADD_DBUS_INTERFACE also apply here.
```
```
macro QT4_ADD_DBUS_ADAPTOR(outfiles xmlfile parentheader parentclassname
[basename] [classname])
create a dbus adaptor (header and implementation file) from the xml file
describing the interface, and add it to the list of sources. The adaptor
forwards the calls to a parent class, defined in parentheader and named
parentclassname. The name of the generated files will be
<basename>adaptor.{cpp,h} where basename defaults to the basename of the
xml file.
If <classname> is provided, then it will be used as the classname of the
adaptor itself.
```
```
macro QT4_GENERATE_DBUS_INTERFACE( header [interfacename] OPTIONS ...)
generate the xml interface file from the given header.
If the optional argument interfacename is omitted, the name of the
interface file is constructed from the basename of the header with
the suffix .xml appended.
Options may be given to qdbuscpp2xml, such as those found when
executing "qdbuscpp2xml --help"
```
```
macro QT4_CREATE_TRANSLATION( qm_files directories ... sources ...
ts_files ... OPTIONS ...)
out: qm_files
in: directories sources ts_files
options: flags to pass to lupdate, such as -extensions to specify
extensions for a directory scan.
generates commands to create .ts (vie lupdate) and .qm
(via lrelease) - files from directories and/or sources. The ts files are
created and/or updated in the source tree (unless given with full paths).
The qm files are generated in the build tree.
Updating the translations can be done by adding the qm_files
to the source list of your library/executable, so they are
always updated, or by adding a custom target to control when
they get updated/generated.
```
```
macro QT4_ADD_TRANSLATION( qm_files ts_files ... )
out: qm_files
in: ts_files
generates commands to create .qm from .ts - files. The generated
filenames can be found in qm_files. The ts_files
must exist and are not updated in any way.
```
```
macro QT4_AUTOMOC(sourcefile1 sourcefile2 ... [TARGET tgt])
The qt4_automoc macro is obsolete. Use the CMAKE_AUTOMOC feature instead.
This macro is still experimental.
It can be used to have moc automatically handled.
So if you have the files foo.h and foo.cpp, and in foo.h a
a class uses the Q_OBJECT macro, moc has to run on it. If you don't
want to use QT4_WRAP_CPP() (which is reliable and mature), you can insert
#include "foo.moc"
in foo.cpp and then give foo.cpp as argument to QT4_AUTOMOC(). This will
scan all listed files at cmake-time for such included moc files and if it
finds them cause a rule to be generated to run moc at build time on the
accompanying header file foo.h.
If a source file has the SKIP_AUTOMOC property set it will be ignored by
this macro.
If the <tgt> is specified, the INTERFACE_INCLUDE_DIRECTORIES and
INTERFACE_COMPILE_DEFINITIONS from the <tgt> are passed to moc.
```
```
function QT4_USE_MODULES( target [link_type] modules...)
This function is obsolete. Use target_link_libraries with IMPORTED targets
instead.
Make <target> use the <modules> from Qt. Using a Qt module means
to link to the library, add the relevant include directories for the
module, and add the relevant compiler defines for using the module.
Modules are roughly equivalent to components of Qt4, so usage would be
something like:
qt4_use_modules(myexe Core Gui Declarative)
to use QtCore, QtGui and QtDeclarative. The optional <link_type> argument
can be specified as either LINK_PUBLIC or LINK_PRIVATE to specify the
same argument to the target_link_libraries call.
```
IMPORTED Targets
----------------
A particular Qt library may be used by using the corresponding [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target with the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command:
```
target_link_libraries(myexe Qt4::QtGui Qt4::QtXml)
```
Using a target in this way causes :cmake(1)` to use the appropriate include directories and compile definitions for the target when compiling `myexe`.
Targets are aware of their dependencies, so for example it is not necessary to list `Qt4::QtCore` if another Qt library is listed, and it is not necessary to list `Qt4::QtGui` if `Qt4::QtDeclarative` is listed. Targets may be tested for existence in the usual way with the [`if(TARGET)`](../command/if#command:if "if") command.
The Qt toolkit may contain both debug and release libraries. [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") will choose the appropriate version based on the build configuration.
`Qt4::QtCore` The QtCore target
`Qt4::QtGui` The QtGui target
`Qt4::Qt3Support` The Qt3Support target
`Qt4::QtAssistant` The QtAssistant target
`Qt4::QtAssistantClient` The QtAssistantClient target
`Qt4::QAxContainer` The QAxContainer target (Windows only)
`Qt4::QAxServer` The QAxServer target (Windows only)
`Qt4::QtDBus` The QtDBus target
`Qt4::QtDeclarative` The QtDeclarative target
`Qt4::QtDesigner` The QtDesigner target
`Qt4::QtDesignerComponents` The QtDesignerComponents target
`Qt4::QtHelp` The QtHelp target
`Qt4::QtMotif` The QtMotif target
`Qt4::QtMultimedia` The QtMultimedia target
`Qt4::QtNetwork` The QtNetwork target
`Qt4::QtNsPLugin` The QtNsPLugin target
`Qt4::QtOpenGL` The QtOpenGL target
`Qt4::QtScript` The QtScript target
`Qt4::QtScriptTools` The QtScriptTools target
`Qt4::QtSql` The QtSql target
`Qt4::QtSvg` The QtSvg target
`Qt4::QtTest` The QtTest target
`Qt4::QtUiTools` The QtUiTools target
`Qt4::QtWebKit` The QtWebKit target
`Qt4::QtXml` The QtXml target
`Qt4::QtXmlPatterns` The QtXmlPatterns target
`Qt4::phonon` The phonon target Result Variables
----------------
Below is a detailed list of variables that FindQt4.cmake sets.
`Qt4_FOUND` If false, don’t try to use Qt 4.
`QT_FOUND` If false, don’t try to use Qt. This variable is for compatibility only.
`QT4_FOUND` If false, don’t try to use Qt 4. This variable is for compatibility only.
`QT_VERSION_MAJOR` The major version of Qt found.
`QT_VERSION_MINOR` The minor version of Qt found.
`QT_VERSION_PATCH` The patch version of Qt found.
| programming_docs |
cmake TestCXXAcceptsFlag TestCXXAcceptsFlag
==================
Deprecated. See [`CheckCXXCompilerFlag`](checkcxxcompilerflag#module:CheckCXXCompilerFlag "CheckCXXCompilerFlag").
Check if the CXX compiler accepts a flag.
```
CHECK_CXX_ACCEPTS_FLAG(<flags> <variable>)
```
`<flags>` the flags to try
`<variable>` variable to store the result
cmake FindSWIG FindSWIG
========
Find SWIG
This module finds an installed SWIG. It sets the following variables:
```
SWIG_FOUND - set to true if SWIG is found
SWIG_DIR - the directory where swig is installed
SWIG_EXECUTABLE - the path to the swig executable
SWIG_VERSION - the version number of the swig executable
```
The minimum required version of SWIG can be specified using the standard syntax, e.g. find\_package(SWIG 1.1)
All information is collected from the SWIG\_EXECUTABLE so the version to be found can be changed from the command line by means of setting SWIG\_EXECUTABLE
cmake FindosgTerrain FindosgTerrain
==============
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgTerrain This module defines
OSGTERRAIN\_FOUND - Was osgTerrain found? OSGTERRAIN\_INCLUDE\_DIR - Where to find the headers OSGTERRAIN\_LIBRARIES - The libraries to link for osgTerrain (use this)
OSGTERRAIN\_LIBRARY - The osgTerrain library OSGTERRAIN\_LIBRARY\_DEBUG - The osgTerrain debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake CPackPackageMaker CPackPackageMaker
=================
PackageMaker CPack generator (Mac OS X).
Variables specific to CPack PackageMaker generator
--------------------------------------------------
The following variable is specific to installers built on Mac OS X using PackageMaker:
`CPACK_OSX_PACKAGE_VERSION`
The version of Mac OS X that the resulting PackageMaker archive should be compatible with. Different versions of Mac OS X support different features. For example, CPack can only build component-based installers for Mac OS X 10.4 or newer, and can only build installers that download component son-the-fly for Mac OS X 10.5 or newer. If left blank, this value will be set to the minimum version of Mac OS X that supports the requested features. Set this variable to some value (e.g., 10.4) only if you want to guarantee that your installer will work on that version of Mac OS X, and don’t mind missing extra features available in the installer shipping with later versions of Mac OS X.
cmake FindXalanC FindXalanC
==========
Find the Apache Xalan-C++ XSL transform processor headers and libraries.
Imported targets
----------------
This module defines the following [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets:
`XalanC::XalanC` The Xalan-C++ `xalan-c` library, if found. Result variables
----------------
This module will set the following variables in your project:
`XalanC_FOUND` true if the Xalan headers and libraries were found
`XalanC_VERSION` Xalan release version
`XalanC_INCLUDE_DIRS` the directory containing the Xalan headers; note `XercesC_INCLUDE_DIRS` is also required
`XalanC_LIBRARIES` Xalan libraries to be linked; note `XercesC_LIBRARIES` is also required Cache variables
---------------
The following cache variables may also be set:
`XalanC_INCLUDE_DIR` the directory containing the Xalan headers
`XalanC_LIBRARY` the Xalan library
cmake FindLibXslt FindLibXslt
===========
Try to find the LibXslt library
Once done this will define
```
LIBXSLT_FOUND - system has LibXslt
LIBXSLT_INCLUDE_DIR - the LibXslt include directory
LIBXSLT_LIBRARIES - Link these to LibXslt
LIBXSLT_DEFINITIONS - Compiler switches required for using LibXslt
LIBXSLT_VERSION_STRING - version of LibXslt found (since CMake 2.8.8)
```
Additionally, the following two variables are set (but not required for using xslt):
`LIBXSLT_EXSLT_LIBRARIES` Link to these if you need to link against the exslt library.
`LIBXSLT_XSLTPROC_EXECUTABLE` Contains the full path to the xsltproc executable if found.
cmake FindDart FindDart
========
Find DART
This module looks for the dart testing software and sets DART\_ROOT to point to where it found it.
cmake CPackBundle CPackBundle
===========
CPack Bundle generator (Mac OS X) specific options
Variables specific to CPack Bundle generator
--------------------------------------------
Installers built on Mac OS X using the Bundle generator use the aforementioned DragNDrop (CPACK\_DMG\_xxx) variables, plus the following Bundle-specific parameters (CPACK\_BUNDLE\_xxx).
`CPACK_BUNDLE_NAME`
The name of the generated bundle. This appears in the OSX finder as the bundle name. Required.
`CPACK_BUNDLE_PLIST`
Path to an OSX plist file that will be used for the generated bundle. This assumes that the caller has generated or specified their own Info.plist file. Required.
`CPACK_BUNDLE_ICON`
Path to an OSX icon file that will be used as the icon for the generated bundle. This is the icon that appears in the OSX finder for the bundle, and in the OSX dock when the bundle is opened. Required.
`CPACK_BUNDLE_STARTUP_COMMAND`
Path to a startup script. This is a path to an executable or script that will be run whenever an end-user double-clicks the generated bundle in the OSX Finder. Optional.
`CPACK_BUNDLE_APPLE_CERT_APP`
The name of your Apple supplied code signing certificate for the application. The name usually takes the form “Developer ID Application: [Name]” or “3rd Party Mac Developer Application: [Name]”. If this variable is not set the application will not be signed.
`CPACK_BUNDLE_APPLE_ENTITLEMENTS`
The name of the plist file that contains your apple entitlements for sandboxing your application. This file is required for submission to the Mac App Store.
`CPACK_BUNDLE_APPLE_CODESIGN_FILES`
A list of additional files that you wish to be signed. You do not need to list the main application folder, or the main executable. You should list any frameworks and plugins that are included in your app bundle.
`CPACK_BUNDLE_APPLE_CODESIGN_PARAMETER`
Additional parameter that will passed to codesign. Default value: “–deep -f”
`CPACK_COMMAND_CODESIGN`
Path to the codesign(1) command used to sign applications with an Apple cert. This variable can be used to override the automatically detected command (or specify its location if the auto-detection fails to find it.)
cmake FindMPI FindMPI
=======
Find a Message Passing Interface (MPI) implementation
The Message Passing Interface (MPI) is a library used to write high-performance distributed-memory parallel applications, and is typically deployed on a cluster. MPI is a standard interface (defined by the MPI forum) for which many implementations are available.
Variables
---------
This module will set the following variables per language in your project, where `<lang>` is one of C, CXX, or Fortran:
`MPI_<lang>_FOUND` Variable indicating the MPI settings for `<lang>` were found.
`MPI_<lang>_COMPILER` MPI Compiler wrapper for `<lang>`.
`MPI_<lang>_COMPILE_FLAGS` Compilation flags for MPI programs, separated by spaces. This is *not* a [;-list](../manual/cmake-language.7#cmake-language-lists).
`MPI_<lang>_INCLUDE_PATH` Include path(s) for MPI header.
`MPI_<lang>_LINK_FLAGS` Linker flags for MPI programs.
`MPI_<lang>_LIBRARIES` All libraries to link MPI programs against. Additionally, the following [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets are defined:
`MPI::MPI_<lang>` Target for using MPI from `<lang>`. Additionally, FindMPI sets the following variables for running MPI programs from the command line:
`MPIEXEC` Executable for running MPI programs, if provided.
`MPIEXEC_NUMPROC_FLAG` Flag to pass to `MPIEXEC` before giving it the number of processors to run on.
`MPIEXEC_MAX_NUMPROCS` Number of MPI processors to utilize. Defaults to the number of processors detected on the host system.
`MPIEXEC_PREFLAGS` Flags to pass to `MPIEXEC` directly before the executable to run.
`MPIEXEC_POSTFLAGS` Flags to pass to `MPIEXEC` after other flags. Usage
-----
To use this module, call `find_package(MPI)`. If you are happy with the auto-detected configuration for your language, then you’re done. If not, you have two options:
1. Set `MPI_<lang>_COMPILER` to the MPI wrapper (e.g. `mpicc`) of your choice and reconfigure. FindMPI will attempt to determine all the necessary variables using *that* compiler’s compile and link flags.
2. If this fails, or if your MPI implementation does not come with a compiler wrapper, then set both `MPI_<lang>_LIBRARIES` and `MPI_<lang>_INCLUDE_PATH`. You may also set any other variables listed above, but these two are required. This will circumvent autodetection entirely.
When configuration is successful, `MPI_<lang>_COMPILER` will be set to the compiler wrapper for `<lang>`, if it was found. `MPI_<lang>_FOUND` and other variables above will be set if any MPI implementation was found for `<lang>`, regardless of whether a compiler was found.
When using `MPIEXEC` to execute MPI applications, you should typically use all of the `MPIEXEC` flags as follows:
```
${MPIEXEC} ${MPIEXEC_NUMPROC_FLAG} ${MPIEXEC_MAX_NUMPROCS}
${MPIEXEC_PREFLAGS} EXECUTABLE ${MPIEXEC_POSTFLAGS} ARGS
```
where `EXECUTABLE` is the MPI program, and `ARGS` are the arguments to pass to the MPI program.
Backward Compatibility
----------------------
For backward compatibility with older versions of FindMPI, these variables are set, but deprecated:
```
MPI_FOUND MPI_COMPILER MPI_LIBRARY
MPI_COMPILE_FLAGS MPI_INCLUDE_PATH MPI_EXTRA_LIBRARY
MPI_LINK_FLAGS MPI_LIBRARIES
```
In new projects, please use the `MPI_<lang>_XXX` equivalents.
cmake FeatureSummary FeatureSummary
==============
Functions for generating a summary of enabled/disabled features.
These functions can be used to generate a summary of enabled and disabled packages and/or feature for a build tree such as:
```
-- The following OPTIONAL packages have been found:
LibXml2 (required version >= 2.4), XML processing lib, <http://xmlsoft.org>
* Enables HTML-import in MyWordProcessor
* Enables odt-export in MyWordProcessor
PNG, A PNG image library., <http://www.libpng.org/pub/png/>
* Enables saving screenshots
-- The following OPTIONAL packages have not been found:
Lua51, The Lua scripting language., <http://www.lua.org>
* Enables macros in MyWordProcessor
Foo, Foo provides cool stuff.
```
Global Properties
-----------------
`FeatureSummary_PKG_TYPES`
The global property [`FeatureSummary_PKG_TYPES`](#variable:FeatureSummary_PKG_TYPES "FeatureSummary_PKG_TYPES") defines the type of packages used by `FeatureSummary`.
The order in this list is important, the first package type in the list is the least important, the last is the most important. the of a package can only be changed to higher types.
The default package types are , `RUNTIME`, `OPTIONAL`, `RECOMMENDED` and `REQUIRED`, and their importance is `RUNTIME < OPTIONAL < RECOMMENDED < REQUIRED`.
`FeatureSummary_REQUIRED_PKG_TYPES`
The global property [`FeatureSummary_REQUIRED_PKG_TYPES`](#variable:FeatureSummary_REQUIRED_PKG_TYPES "FeatureSummary_REQUIRED_PKG_TYPES") defines which package types are required.
If one or more package in this categories has not been found, CMake will abort when calling [`feature_summary()`](#command:feature_summary "feature_summary") with the ‘FATAL\_ON\_MISSING\_REQUIRED\_PACKAGES’ option enabled.
The default value for this global property is `REQUIRED`.
`FeatureSummary_DEFAULT_PKG_TYPE`
The global property [`FeatureSummary_DEFAULT_PKG_TYPE`](#variable:FeatureSummary_DEFAULT_PKG_TYPE "FeatureSummary_DEFAULT_PKG_TYPE") defines which package type is the default one. When calling [`feature_summary()`](#command:feature_summary "feature_summary"), if the user did not set the package type explicitly, the package will be assigned to this category.
This value must be one of the types defined in the [`FeatureSummary_PKG_TYPES`](#variable:FeatureSummary_PKG_TYPES "FeatureSummary_PKG_TYPES") global property unless the package type is set for all the packages.
The default value for this global property is `OPTIONAL`.
`FeatureSummary_<TYPE>_DESCRIPTION`
The global property [`FeatureSummary_<TYPE>_DESCRIPTION`](#variable:FeatureSummary_<TYPE>_DESCRIPTION "FeatureSummary_<TYPE>_DESCRIPTION") can be defined for each type to replace the type name with the specified string whenever the package type is used in an output string.
If not set, the string “`<TYPE>` packages” is used.
Functions
---------
`feature_summary`
```
feature_summary( [FILENAME <file>]
[APPEND]
[VAR <variable_name>]
[INCLUDE_QUIET_PACKAGES]
[FATAL_ON_MISSING_REQUIRED_PACKAGES]
[DESCRIPTION "<description>" | DEFAULT_DESCRIPTION]
[QUIET_ON_EMPTY]
WHAT (ALL
| PACKAGES_FOUND | PACKAGES_NOT_FOUND
| <TYPE>_PACKAGES_FOUND | <TYPE>_PACKAGES_NOT_FOUND
| ENABLED_FEATURES | DISABLED_FEATURES)
)
```
The `feature_summary()` macro can be used to print information about enabled or disabled packages or features of a project. By default, only the names of the features/packages will be printed and their required version when one was specified. Use `set_package_properties()` to add more useful information, like e.g. a download URL for the respective package or their purpose in the project.
The `WHAT` option is the only mandatory option. Here you specify what information will be printed:
`ALL` print everything
`ENABLED_FEATURES` the list of all features which are enabled
`DISABLED_FEATURES` the list of all features which are disabled
`PACKAGES_FOUND` the list of all packages which have been found
`PACKAGES_NOT_FOUND` the list of all packages which have not been found For each package type `<TYPE>` defined by the [`FeatureSummary_PKG_TYPES`](#variable:FeatureSummary_PKG_TYPES "FeatureSummary_PKG_TYPES") global property, the following information can also be used:
`<TYPE>_PACKAGES_FOUND` only those packages which have been found which have the type <TYPE>
`<TYPE>_PACKAGES_NOT_FOUND` only those packages which have not been found which have the type <TYPE> With the exception of the `ALL` value, these values can be combined in order to customize the output. For example:
```
feature_summary(WHAT ENABLED_FEATURES DISABLED_FEATURES)
```
If a `FILENAME` is given, the information is printed into this file. If `APPEND` is used, it is appended to this file, otherwise the file is overwritten if it already existed. If the VAR option is used, the information is “printed” into the specified variable. If `FILENAME` is not used, the information is printed to the terminal. Using the `DESCRIPTION` option a description or headline can be set which will be printed above the actual content. If only one type of package was requested, no title is printed, unless it is explicitly set using either `DESCRIPTION` to use a custom string, or `DEFAULT_DESCRIPTION` to use a default title for the requested type. If `INCLUDE_QUIET_PACKAGES` is given, packages which have been searched with `find_package(... QUIET)` will also be listed. By default they are skipped. If `FATAL_ON_MISSING_REQUIRED_PACKAGES` is given, CMake will abort if a package which is marked as one of the package types listed in the [`FeatureSummary_REQUIRED_PKG_TYPES`](#variable:FeatureSummary_REQUIRED_PKG_TYPES "FeatureSummary_REQUIRED_PKG_TYPES") global property has not been found. The default value for the [`FeatureSummary_REQUIRED_PKG_TYPES`](#variable:FeatureSummary_REQUIRED_PKG_TYPES "FeatureSummary_REQUIRED_PKG_TYPES") global property is `REQUIRED`.
The [`FeatureSummary_DEFAULT_PKG_TYPE`](#variable:FeatureSummary_DEFAULT_PKG_TYPE "FeatureSummary_DEFAULT_PKG_TYPE") global property can be modified to change the default package type assigned when not explicitly assigned by the user.
If the `QUIET_ON_EMPTY` option is used, if only one type of package was requested, and no packages belonging to that category were found, then no output (including the `DESCRIPTION`) is printed or added to the `VAR` variable.
Example 1, append everything to a file:
```
include(FeatureSummary)
feature_summary(WHAT ALL
FILENAME ${CMAKE_BINARY_DIR}/all.log APPEND)
```
Example 2, print the enabled features into the variable enabledFeaturesText, including QUIET packages:
```
include(FeatureSummary)
feature_summary(WHAT ENABLED_FEATURES
INCLUDE_QUIET_PACKAGES
DESCRIPTION "Enabled Features:"
VAR enabledFeaturesText)
message(STATUS "${enabledFeaturesText}")
```
Example 3, change default package types and print only the categories that are not empty:
```
include(FeatureSummary)
set_property(GLOBAL APPEND PROPERTY FeatureSummary_PKG_TYPES BUILD)
find_package(FOO)
set_package_properties(FOO PROPERTIES TYPE BUILD)
feature_summary(WHAT BUILD_PACKAGES_FOUND
Description "Build tools found:"
QUIET_ON_EMPTY)
feature_summary(WHAT BUILD_PACKAGES_NOT_FOUND
Description "Build tools not found:"
QUIET_ON_EMPTY)
```
`set_package_properties`
```
set_package_properties(<name> PROPERTIES
[ URL <url> ]
[ DESCRIPTION <description> ]
[ TYPE (RUNTIME|OPTIONAL|RECOMMENDED|REQUIRED) ]
[ PURPOSE <purpose> ]
)
```
Use this macro to set up information about the named package, which can then be displayed via FEATURE\_SUMMARY(). This can be done either directly in the Find-module or in the project which uses the module after the find\_package() call. The features for which information can be set are added automatically by the find\_package() command.
`URL <url>` This should be the homepage of the package, or something similar. Ideally this is set already directly in the Find-module.
`DESCRIPTION <description>` A short description what that package is, at most one sentence. Ideally this is set already directly in the Find-module.
`TYPE <type>` What type of dependency has the using project on that package. Default is `OPTIONAL`. In this case it is a package which can be used by the project when available at buildtime, but it also work without. `RECOMMENDED` is similar to `OPTIONAL`, i.e. the project will build if the package is not present, but the functionality of the resulting binaries will be severly limited. If a `REQUIRED` package is not available at buildtime, the project may not even build. This can be combined with the `FATAL_ON_MISSING_REQUIRED_PACKAGES` argument for `feature_summary()`. Last, a `RUNTIME` package is a package which is actually not used at all during the build, but which is required for actually running the resulting binaries. So if such a package is missing, the project can still be built, but it may not work later on. If `set_package_properties()` is called multiple times for the same package with different TYPEs, the `TYPE` is only changed to higher TYPEs (`RUNTIME < OPTIONAL < RECOMMENDED < REQUIRED`), lower TYPEs are ignored. The `TYPE` property is project-specific, so it cannot be set by the Find-module, but must be set in the project. Type accepted can be changed by setting the [`FeatureSummary_PKG_TYPES`](#variable:FeatureSummary_PKG_TYPES "FeatureSummary_PKG_TYPES") global property.
`PURPOSE <purpose>` This describes which features this package enables in the project, i.e. it tells the user what functionality he gets in the resulting binaries. If set\_package\_properties() is called multiple times for a package, all PURPOSE properties are appended to a list of purposes of the package in the project. As the TYPE property, also the PURPOSE property is project-specific, so it cannot be set by the Find-module, but must be set in the project. Example for setting the info for a package:
```
find_package(LibXml2)
set_package_properties(LibXml2 PROPERTIES
DESCRIPTION "A XML processing library."
URL "http://xmlsoft.org/")
# or
set_package_properties(LibXml2 PROPERTIES
TYPE RECOMMENDED
PURPOSE "Enables HTML-import in MyWordProcessor")
# or
set_package_properties(LibXml2 PROPERTIES
TYPE OPTIONAL
PURPOSE "Enables odt-export in MyWordProcessor")
find_package(DBUS)
set_package_properties(DBUS PROPERTIES
TYPE RUNTIME
PURPOSE "Necessary to disable the screensaver during a presentation")
```
`add_feature_info`
```
add_feature_info(<name> <enabled> <description>)
```
Use this macro to add information about a feature with the given `<name>`. `<enabled>` contains whether this feature is enabled or not. It can be a variable or a list of conditions. `<description>` is a text describing the feature. The information can be displayed using `feature_summary()` for `ENABLED_FEATURES` and `DISABLED_FEATURES` respectively.
Example for setting the info for a feature:
```
option(WITH_FOO "Help for foo" ON)
add_feature_info(Foo WITH_FOO "The Foo feature provides very cool stuff.")
```
Legacy Macros
-------------
The following macros are provided for compatibility with previous CMake versions:
`set_package_info`
```
set_package_info(<name> <description> [ <url> [<purpose>] ])
```
Use this macro to set up information about the named package, which can then be displayed via `feature_summary()`. This can be done either directly in the Find-module or in the project which uses the module after the [`find_package()`](../command/find_package#command:find_package "find_package") call. The features for which information can be set are added automatically by the `find_package()` command.
`set_feature_info`
```
set_feature_info(<name> <description> [<url>])
```
Does the same as:
```
set_package_info(<name> <description> <url>)
```
`print_enabled_features`
```
print_enabled_features()
```
Does the same as
```
feature_summary(WHAT ENABLED_FEATURES DESCRIPTION "Enabled features:")
```
`print_disabled_features`
```
print_disabled_features()
```
Does the same as
```
feature_summary(WHAT DISABLED_FEATURES DESCRIPTION "Disabled features:")
```
| programming_docs |
cmake FindKDE3 FindKDE3
========
Find the KDE3 include and library dirs, KDE preprocessors and define a some macros
This module defines the following variables:
`KDE3_DEFINITIONS` compiler definitions required for compiling KDE software
`KDE3_INCLUDE_DIR` the KDE include directory
`KDE3_INCLUDE_DIRS` the KDE and the Qt include directory, for use with include\_directories()
`KDE3_LIB_DIR` the directory where the KDE libraries are installed, for use with link\_directories()
`QT_AND_KDECORE_LIBS` this contains both the Qt and the kdecore library
`KDE3_DCOPIDL_EXECUTABLE` the dcopidl executable
`KDE3_DCOPIDL2CPP_EXECUTABLE` the dcopidl2cpp executable
`KDE3_KCFGC_EXECUTABLE` the kconfig\_compiler executable
`KDE3_FOUND` set to TRUE if all of the above has been found The following user adjustable options are provided:
`KDE3_BUILD_TESTS` enable this to build KDE testcases It also adds the following macros (from KDE3Macros.cmake) SRCS\_VAR is always the variable which contains the list of source files for your application or library.
KDE3\_AUTOMOC(file1 … fileN)
```
Call this if you want to have automatic moc file handling.
This means if you include "foo.moc" in the source file foo.cpp
a moc file for the header foo.h will be created automatically.
You can set the property SKIP_AUTOMAKE using set_source_files_properties()
to exclude some files in the list from being processed.
```
KDE3\_ADD\_MOC\_FILES(SRCS\_VAR file1 … fileN )
```
If you don't use the KDE3_AUTOMOC() macro, for the files
listed here moc files will be created (named "foo.moc.cpp")
```
KDE3\_ADD\_DCOP\_SKELS(SRCS\_VAR header1.h … headerN.h )
```
Use this to generate DCOP skeletions from the listed headers.
```
KDE3\_ADD\_DCOP\_STUBS(SRCS\_VAR header1.h … headerN.h )
```
Use this to generate DCOP stubs from the listed headers.
```
KDE3\_ADD\_UI\_FILES(SRCS\_VAR file1.ui … fileN.ui )
```
Use this to add the Qt designer ui files to your application/library.
```
KDE3\_ADD\_KCFG\_FILES(SRCS\_VAR file1.kcfgc … fileN.kcfgc )
```
Use this to add KDE kconfig compiler files to your application/library.
```
KDE3\_INSTALL\_LIBTOOL\_FILE(target)
```
This will create and install a simple libtool file for the given target.
```
KDE3\_ADD\_EXECUTABLE(name file1 … fileN )
```
Currently identical to add_executable(), may provide some advanced
features in the future.
```
KDE3\_ADD\_KPART(name [WITH\_PREFIX] file1 … fileN )
```
Create a KDE plugin (KPart, kioslave, etc.) from the given source files.
If WITH_PREFIX is given, the resulting plugin will have the prefix "lib",
otherwise it won't.
It creates and installs an appropriate libtool la-file.
```
KDE3\_ADD\_KDEINIT\_EXECUTABLE(name file1 … fileN )
```
Create a KDE application in the form of a module loadable via kdeinit.
A library named kdeinit_<name> will be created and a small executable
which links to it.
```
The option KDE3\_ENABLE\_FINAL to enable all-in-one compilation is no longer supported.
Author: Alexander Neundorf <[[email protected]](mailto:neundorf%40kde.org)>
cmake FindWget FindWget
========
Find wget
This module looks for wget. This module defines the following values:
```
WGET_EXECUTABLE: the full path to the wget tool.
WGET_FOUND: True if wget has been found.
```
cmake CheckCSourceCompiles CheckCSourceCompiles
====================
Check if given C source compiles and links into an executable
CHECK\_C\_SOURCE\_COMPILES(<code> <var> [FAIL\_REGEX <fail-regex>])
```
<code> - source code to try to compile, must define 'main'
<var> - variable to store whether the source code compiled
Will be created as an internal cache variable.
<fail-regex> - fail if test output matches this regex
```
The following variables may be set before calling this macro to modify the way the check is run:
```
CMAKE_REQUIRED_FLAGS = string of compile command line flags
CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
CMAKE_REQUIRED_INCLUDES = list of include directories
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
CMAKE_REQUIRED_QUIET = execute quietly without messages
```
cmake FindosgParticle FindosgParticle
===============
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgParticle This module defines
OSGPARTICLE\_FOUND - Was osgParticle found? OSGPARTICLE\_INCLUDE\_DIR - Where to find the headers OSGPARTICLE\_LIBRARIES - The libraries to link for osgParticle (use this)
OSGPARTICLE\_LIBRARY - The osgParticle library OSGPARTICLE\_LIBRARY\_DEBUG - The osgParticle debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake UseSWIG UseSWIG
=======
Defines the following macros for use with SWIG:
```
SWIG_ADD_LIBRARY(<name>
[TYPE <SHARED|MODULE|STATIC|USE_BUILD_SHARED_LIBS>]
LANGUAGE <language>
SOURCES <file>...
)
- Define swig module with given name and specified language
SWIG_LINK_LIBRARIES(name [ libraries ])
- Link libraries to swig module
```
Source files properties on module files can be set before the invocation of the SWIG\_ADD\_LIBRARY macro to specify special behavior of SWIG.
The source file property CPLUSPLUS calls SWIG in c++ mode, e.g.:
```
set_property(SOURCE mymod.i PROPERTY CPLUSPLUS ON)
swig_add_library(mymod LANGUAGE python SOURCES mymod.i)
```
The source file property SWIG\_FLAGS adds custom flags to the SWIG executable.
The source-file property SWIG\_MODULE\_NAME have to be provided to specify the actual import name of the module in the target language if it cannot be scanned automatically from source or different from the module file basename.:
```
set_property(SOURCE mymod.i PROPERTY SWIG_MODULE_NAME mymod_realname)
```
To get the name of the swig module target library, use: ${SWIG\_MODULE\_${name}\_REAL\_NAME}.
Also some variables can be set to specify special behavior of SWIG.
CMAKE\_SWIG\_FLAGS can be used to add special flags to all swig calls.
CMAKE\_SWIG\_OUTDIR allows one to specify where to write the language specific files (swig -outdir option).
SWIG\_OUTFILE\_DIR allows one to specify where to write the output file (swig -o option). If not specified, CMAKE\_SWIG\_OUTDIR is used.
The name-specific variable SWIG\_MODULE\_<name>\_EXTRA\_DEPS may be used to specify extra dependencies for the generated modules.
If the source file generated by swig need some special flag you can use:
```
set_source_files_properties( ${swig_generated_file_fullname}
PROPERTIES COMPILE_FLAGS "-bla")
```
cmake ExternalProject ExternalProject
===============
Create custom targets to build projects in external trees
`ExternalProject_Add`
The `ExternalProject_Add` function creates a custom target to drive download, update/patch, configure, build, install and test steps of an external project:
```
ExternalProject_Add(<name> [<option>...])
```
General options are:
`DEPENDS <projects>...` Targets on which the project depends
`PREFIX <dir>` Root dir for entire project
`LIST_SEPARATOR <sep>` Sep to be replaced by ; in cmd lines
`TMP_DIR <dir>` Directory to store temporary files
`STAMP_DIR <dir>` Directory to store step timestamps
`EXCLUDE_FROM_ALL 1` The “all” target does not depend on this Download step options are:
`DOWNLOAD_NAME <fname>` File name to store (if not end of URL)
`DOWNLOAD_DIR <dir>` Directory to store downloaded files
`DOWNLOAD_COMMAND <cmd>...` Command to download source tree
`DOWNLOAD_NO_PROGRESS 1` Disable download progress reports
`CVS_REPOSITORY <cvsroot>` CVSROOT of CVS repository
`CVS_MODULE <mod>` Module to checkout from CVS repo
`CVS_TAG <tag>` Tag to checkout from CVS repo
`SVN_REPOSITORY <url>` URL of Subversion repo
`SVN_REVISION -r<rev>` Revision to checkout from Subversion repo
`SVN_USERNAME <username>` Username for Subversion checkout and update
`SVN_PASSWORD <password>` Password for Subversion checkout and update
`SVN_TRUST_CERT 1` Trust the Subversion server site certificate
`GIT_REPOSITORY <url>` URL of git repo
`GIT_TAG <tag>` Git branch name, commit id or tag
`GIT_REMOTE_NAME <name>` The optional name of the remote, default to `origin`
`GIT_SUBMODULES <module>...` Git submodules that shall be updated, all if empty
`GIT_SHALLOW 1` Tell Git to clone with `--depth 1`. Use when `GIT_TAG` is not specified or when it names a branch in order to download only the tip of the branch without the rest of its history.
`GIT_PROGRESS 1` Tell Git to clone with `--progress`. For large projects, the clone step does not output anything which can make the build appear to have stalled. This option forces Git to output progress information during the clone step so that forward progress is indicated.
`GIT_CONFIG <option>...` Tell Git to clone with `--config <option>`. Use additional configuration parameters when cloning the project (`key=value` as expected by `git
config`).
`HG_REPOSITORY <url>` URL of mercurial repo
`HG_TAG <tag>` Mercurial branch name, commit id or tag
`URL /.../src.tgz [/.../src.tgz]...` Full path or URL(s) of source. Multiple URLs are allowed as mirrors.
`URL_HASH ALGO=value` Hash of file at URL
`URL_MD5 md5` Equivalent to URL\_HASH MD5=md5
`HTTP_USERNAME <username>` Username for download operation
`HTTP_PASSWORD <username>` Password for download operation
`HTTP_HEADER <header>` HTTP header for download operation. Suboption can be repeated several times.
`TLS_VERIFY <bool>` Should certificate for https be checked
`TLS_CAINFO <file>` Path to a certificate authority file
`TIMEOUT <seconds>` Time allowed for file download operations
`DOWNLOAD_NO_EXTRACT 1` Just download the file and do not extract it; the full path to the downloaded file is available as `<DOWNLOADED_FILE>`. Update/Patch step options are:
`UPDATE_COMMAND <cmd>...` Source work-tree update command
`UPDATE_DISCONNECTED 1` Never update automatically from the remote repository
`PATCH_COMMAND <cmd>...` Command to patch downloaded source Configure step options are:
`SOURCE_DIR <dir>` Source dir to be used for build
`SOURCE_SUBDIR <dir>` Path to source CMakeLists.txt relative to `SOURCE_DIR`
`CONFIGURE_COMMAND <cmd>...` Build tree configuration command
`CMAKE_COMMAND /.../cmake` Specify alternative cmake executable
`CMAKE_GENERATOR <gen>` Specify generator for native build
`CMAKE_GENERATOR_PLATFORM <platform>` Generator-specific platform name
`CMAKE_GENERATOR_TOOLSET <toolset>` Generator-specific toolset name
`CMAKE_ARGS <arg>...` Arguments to CMake command line. These arguments are passed to CMake command line, and can contain arguments other than cache values, see also [`CMake Options`](../manual/cmake.1#manual:cmake(1) "cmake(1)"). Arguments in the form `-Dvar:string=on` are always passed to the command line, and therefore cannot be changed by the user. Arguments may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)").
`CMAKE_CACHE_ARGS <arg>...` Initial cache arguments, of the form `-Dvar:string=on`. These arguments are written in a pre-load a script that populates CMake cache, see also [`cmake -C`](../manual/cmake.1#manual:cmake(1) "cmake(1)"). This allows one to overcome command line length limits. These arguments are [`set()`](../command/set#command:set "set") using the `FORCE` argument, and therefore cannot be changed by the user. Arguments may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)").
`CMAKE_CACHE_DEFAULT_ARGS <arg>...` Initial default cache arguments, of the form `-Dvar:string=on`. These arguments are written in a pre-load a script that populates CMake cache, see also [`cmake -C`](../manual/cmake.1#manual:cmake(1) "cmake(1)"). This allows one to overcome command line length limits. These arguments can be used as default value that will be set if no previous value is found in the cache, and that the user can change later. Arguments may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)"). Build step options are:
`BINARY_DIR <dir>` Specify build dir location
`BUILD_COMMAND <cmd>...` Command to drive the native build
`BUILD_IN_SOURCE 1` Use source dir for build dir
`BUILD_ALWAYS 1` No stamp file, build step always runs
`BUILD_BYPRODUCTS <file>...` Files that will be generated by the build command but may or may not have their modification time updated by subsequent builds. Install step options are:
`INSTALL_DIR <dir>` Installation prefix to be placed in the `<INSTALL_DIR>` placeholder. This does not actually configure the external project to install to the given prefix. That must be done by passing appropriate arguments to the external project configuration step, e.g. using `<INSTALL_DIR>`.
`INSTALL_COMMAND <cmd>...` Command to drive installation of the external project after it has been built. This only happens at the *build* time of the calling project. In order to install files from the external project alongside the locally-built files, a separate local [`install()`](../command/install#command:install "install") call must be added to pick the files up from one of the external project trees. Test step options are:
`TEST_BEFORE_INSTALL 1` Add test step executed before install step
`TEST_AFTER_INSTALL 1` Add test step executed after install step
`TEST_EXCLUDE_FROM_MAIN 1` Main target does not depend on the test step
`TEST_COMMAND <cmd>...` Command to drive test Output logging options are:
`LOG_DOWNLOAD 1` Wrap download in script to log output
`LOG_UPDATE 1` Wrap update in script to log output
`LOG_CONFIGURE 1` Wrap configure in script to log output
`LOG_BUILD 1` Wrap build in script to log output
`LOG_TEST 1` Wrap test in script to log output
`LOG_INSTALL 1` Wrap install in script to log output Steps can be given direct access to the terminal if possible. With the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator, this places the steps in the `console` [`pool`](../prop_gbl/job_pools#prop_gbl:JOB_POOLS "JOB_POOLS"). Options are:
`USES_TERMINAL_DOWNLOAD 1` Give download terminal access.
`USES_TERMINAL_UPDATE 1` Give update terminal access.
`USES_TERMINAL_CONFIGURE 1` Give configure terminal access.
`USES_TERMINAL_BUILD 1` Give build terminal access.
`USES_TERMINAL_TEST 1` Give test terminal access.
`USES_TERMINAL_INSTALL 1` Give install terminal access. Other options are:
`STEP_TARGETS <step-target>...` Generate custom targets for these steps
`INDEPENDENT_STEP_TARGETS <step-target>...` Generate custom targets for these steps that do not depend on other external projects even if a dependency is set The `*_DIR` options specify directories for the project, with default directories computed as follows. If the `PREFIX` option is given to `ExternalProject_Add()` or the `EP_PREFIX` directory property is set, then an external project is built and installed under the specified prefix:
```
TMP_DIR = <prefix>/tmp
STAMP_DIR = <prefix>/src/<name>-stamp
DOWNLOAD_DIR = <prefix>/src
SOURCE_DIR = <prefix>/src/<name>
BINARY_DIR = <prefix>/src/<name>-build
INSTALL_DIR = <prefix>
```
Otherwise, if the `EP_BASE` directory property is set then components of an external project are stored under the specified base:
```
TMP_DIR = <base>/tmp/<name>
STAMP_DIR = <base>/Stamp/<name>
DOWNLOAD_DIR = <base>/Download/<name>
SOURCE_DIR = <base>/Source/<name>
BINARY_DIR = <base>/Build/<name>
INSTALL_DIR = <base>/Install/<name>
```
If no `PREFIX`, `EP_PREFIX`, or `EP_BASE` is specified then the default is to set `PREFIX` to `<name>-prefix`. Relative paths are interpreted with respect to the build directory corresponding to the source directory in which `ExternalProject_Add` is invoked.
If `SOURCE_SUBDIR` is set and no `CONFIGURE_COMMAND` is specified, the configure command will run CMake using the `CMakeLists.txt` located in the relative path specified by `SOURCE_SUBDIR`, relative to the `SOURCE_DIR`. If no `SOURCE_SUBDIR` is given, `SOURCE_DIR` is used.
If `SOURCE_DIR` is explicitly set to an existing directory the project will be built from it. Otherwise a download step must be specified using one of the `DOWNLOAD_COMMAND`, `CVS_*`, `SVN_*`, or `URL` options. The `URL` option may refer locally to a directory or source tarball, or refer to a remote tarball (e.g. `http://.../src.tgz`).
If `UPDATE_DISCONNECTED` is set, the update step is not executed automatically when building the main target. The update step can still be added as a step target and called manually. This is useful if you want to allow one to build the project when you are disconnected from the network (you might still need the network for the download step). This is disabled by default. The directory property `EP_UPDATE_DISCONNECTED` can be used to change the default value for all the external projects in the current directory and its subdirectories.
`ExternalProject_Add_Step`
The `ExternalProject_Add_Step` function adds a custom step to an external project:
```
ExternalProject_Add_Step(<name> <step> [<option>...])
```
Options are:
`COMMAND <cmd>...` Command line invoked by this step
`COMMENT "<text>..."` Text printed when step executes
`DEPENDEES <step>...` Steps on which this step depends
`DEPENDERS <step>...` Steps that depend on this step
`DEPENDS <file>...` Files on which this step depends
`BYPRODUCTS <file>...` Files that will be generated by this step but may or may not have their modification time updated by subsequent builds.
`ALWAYS 1` No stamp file, step always runs
`EXCLUDE_FROM_MAIN 1` Main target does not depend on this step
`WORKING_DIRECTORY <dir>` Working directory for command
`LOG 1` Wrap step in script to log output
`USES_TERMINAL 1` Give the step direct access to the terminal if possible. The command line, comment, working directory, and byproducts of every standard and custom step are processed to replace tokens `<SOURCE_DIR>`, `<SOURCE_SUBDIR>`, `<BINARY_DIR>`, `<INSTALL_DIR>`, and `<TMP_DIR>` with corresponding property values.
Any builtin step that specifies a `<step>_COMMAND cmd...` or custom step that specifies a `COMMAND cmd...` may specify additional command lines using the form `COMMAND cmd...`. At build time the commands will be executed in order and aborted if any one fails. For example:
```
... BUILD_COMMAND make COMMAND echo done ...
```
specifies to run `make` and then `echo done` during the build step. Whether the current working directory is preserved between commands is not defined. Behavior of shell operators like `&&` is not defined.
Arguments to `<step>_COMMAND` or `COMMAND` options may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)").
`ExternalProject_Get_Property`
The `ExternalProject_Get_Property` function retrieves external project target properties:
```
ExternalProject_Get_Property(<name> [prop1 [prop2 [...]]])
```
It stores property values in variables of the same name. Property names correspond to the keyword argument names of `ExternalProject_Add`.
`ExternalProject_Add_StepTargets`
The `ExternalProject_Add_StepTargets` function generates custom targets for the steps listed:
```
ExternalProject_Add_StepTargets(<name> [NO_DEPENDS] [step1 [step2 [...]]])
```
If `NO_DEPENDS` is set, the target will not depend on the dependencies of the complete project. This is usually safe to use for the download, update, and patch steps that do not require that all the dependencies are updated and built. Using `NO_DEPENDS` for other of the default steps might break parallel builds, so you should avoid, it. For custom steps, you should consider whether or not the custom commands requires that the dependencies are configured, built and installed.
If `STEP_TARGETS` or `INDEPENDENT_STEP_TARGETS` is set then `ExternalProject_Add_StepTargets` is automatically called at the end of matching calls to `ExternalProject_Add_Step`. Pass `STEP_TARGETS` or `INDEPENDENT_STEP_TARGETS` explicitly to individual `ExternalProject_Add` calls, or implicitly to all `ExternalProject_Add` calls by setting the directory properties `EP_STEP_TARGETS` and `EP_INDEPENDENT_STEP_TARGETS`. The `INDEPENDENT` version of the argument and of the property will call `ExternalProject_Add_StepTargets` with the `NO_DEPENDS` argument.
If `STEP_TARGETS` and `INDEPENDENT_STEP_TARGETS` are not set, clients may still manually call `ExternalProject_Add_StepTargets` after calling `ExternalProject_Add` or `ExternalProject_Add_Step`.
This functionality is provided to make it easy to drive the steps independently of each other by specifying targets on build command lines. For example, you may be submitting to a sub-project based dashboard, where you want to drive the configure portion of the build, then submit to the dashboard, followed by the build portion, followed by tests. If you invoke a custom target that depends on a step halfway through the step dependency chain, then all the previous steps will also run to ensure everything is up to date.
For example, to drive configure, build and test steps independently for each `ExternalProject_Add` call in your project, write the following line prior to any `ExternalProject_Add` calls in your `CMakeLists.txt` file:
```
set_property(DIRECTORY PROPERTY EP_STEP_TARGETS configure build test)
```
`ExternalProject_Add_StepDependencies`
The `ExternalProject_Add_StepDependencies` function add some dependencies for some external project step:
```
ExternalProject_Add_StepDependencies(<name> <step> [target1 [target2 [...]]])
```
This function takes care to set both target and file level dependencies, and will ensure that parallel builds will not break. It should be used instead of [`add_dependencies()`](../command/add_dependencies#command:add_dependencies "add_dependencies") when adding a dependency for some of the step targets generated by `ExternalProject`.
| programming_docs |
cmake CPackArchive CPackArchive
============
Archive CPack generator that supports packaging of sources and binaries in different formats:
* 7Z - 7zip - (.7z)
* TBZ2 (.tar.bz2)
* TGZ (.tar.gz)
* TXZ (.tar.xz)
* TZ (.tar.Z)
* ZIP (.zip)
Variables specific to CPack Archive generator
---------------------------------------------
`CPACK_ARCHIVE_FILE_NAME`
`CPACK_ARCHIVE_<component>_FILE_NAME`
Package file name without extension which is added automatically depending on the archive format.
* Mandatory : YES
* `Default : <CPACK_PACKAGE_FILE_NAME>[-<component>].<extension> with`
spaces replaced by ‘-‘
`CPACK_ARCHIVE_COMPONENT_INSTALL`
Enable component packaging for CPackArchive
* Mandatory : NO
* Default : OFF
If enabled (ON) multiple packages are generated. By default a single package containing files of all components is generated.
cmake CheckStructHasMember CheckStructHasMember
====================
Check if the given struct or class has the specified member variable
```
CHECK_STRUCT_HAS_MEMBER(<struct> <member> <header> <variable>
[LANGUAGE <language>])
```
```
<struct> - the name of the struct or class you are interested in
<member> - the member which existence you want to check
<header> - the header(s) where the prototype should be declared
<variable> - variable to store the result
<language> - the compiler to use (C or CXX)
```
The following variables may be set before calling this macro to modify the way the check is run:
```
CMAKE_REQUIRED_FLAGS = string of compile command line flags
CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
CMAKE_REQUIRED_INCLUDES = list of include directories
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
CMAKE_REQUIRED_QUIET = execute quietly without messages
```
Example: CHECK\_STRUCT\_HAS\_MEMBER(“struct timeval” tv\_sec sys/select.h HAVE\_TIMEVAL\_TV\_SEC LANGUAGE C)
cmake CheckIncludeFile CheckIncludeFile
================
Provides a macro to check if a header file can be included in `C`.
`CHECK_INCLUDE_FILE`
```
CHECK_INCLUDE_FILE(<include> <variable> [<flags>])
```
Check if the given `<include>` file may be included in a `C` source file and store the result in an internal cache entry named `<variable>`. The optional third argument may be used to add compilation flags to the check (or use `CMAKE_REQUIRED_FLAGS` below).
The following variables may be set before calling this macro to modify the way the check is run:
`CMAKE_REQUIRED_FLAGS` string of compile command line flags
`CMAKE_REQUIRED_DEFINITIONS` list of macros to define (-DFOO=bar)
`CMAKE_REQUIRED_INCLUDES` list of include directories
`CMAKE_REQUIRED_QUIET` execute quietly without messages See the [`CheckIncludeFiles`](checkincludefiles#module:CheckIncludeFiles "CheckIncludeFiles") module to check for multiple headers at once. See the [`CheckIncludeFileCXX`](checkincludefilecxx#module:CheckIncludeFileCXX "CheckIncludeFileCXX") module to check for headers using the `CXX` language.
cmake FindPHP4 FindPHP4
========
Find PHP4
This module finds if PHP4 is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:
```
PHP4_INCLUDE_PATH = path to where php.h can be found
PHP4_EXECUTABLE = full path to the php4 binary
```
cmake WriteCompilerDetectionHeader WriteCompilerDetectionHeader
============================
This module provides the function write\_compiler\_detection\_header().
The `WRITE_COMPILER_DETECTION_HEADER` function can be used to generate a file suitable for preprocessor inclusion which contains macros to be used in source code:
```
write_compiler_detection_header(
FILE <file>
PREFIX <prefix>
[OUTPUT_FILES_VAR <output_files_var> OUTPUT_DIR <output_dir>]
COMPILERS <compiler> [...]
FEATURES <feature> [...]
[VERSION <version>]
[PROLOG <prolog>]
[EPILOG <epilog>]
[ALLOW_UNKNOWN_COMPILERS]
[ALLOW_UNKNOWN_COMPILER_VERSIONS]
)
```
The `write_compiler_detection_header` function generates the file `<file>` with macros which all have the prefix `<prefix>`.
By default, all content is written directly to the `<file>`. The `OUTPUT_FILES_VAR` may be specified to cause the compiler-specific content to be written to separate files. The separate files are then available in the `<output_files_var>` and may be consumed by the caller for installation for example. The `OUTPUT_DIR` specifies a relative path from the main `<file>` to the compiler-specific files. For example:
```
write_compiler_detection_header(
FILE climbingstats_compiler_detection.h
PREFIX ClimbingStats
OUTPUT_FILES_VAR support_files
OUTPUT_DIR compilers
COMPILERS GNU Clang MSVC Intel
FEATURES cxx_variadic_templates
)
install(FILES
${CMAKE_CURRENT_BINARY_DIR}/climbingstats_compiler_detection.h
DESTINATION include
)
install(FILES
${support_files}
DESTINATION include/compilers
)
```
`VERSION` may be used to specify the API version to be generated. Future versions of CMake may introduce alternative APIs. A given API is selected by any `<version>` value greater than or equal to the version of CMake that introduced the given API and less than the version of CMake that introduced its succeeding API. The value of the [`CMAKE_MINIMUM_REQUIRED_VERSION`](../variable/cmake_minimum_required_version#variable:CMAKE_MINIMUM_REQUIRED_VERSION "CMAKE_MINIMUM_REQUIRED_VERSION") variable is used if no explicit version is specified. (As of CMake version 3.9.6 there is only one API version.)
`PROLOG` may be specified as text content to write at the start of the header. `EPILOG` may be specified as text content to write at the end of the header
At least one `<compiler>` and one `<feature>` must be listed. Compilers which are known to CMake, but not specified are detected and a preprocessor `#error` is generated for them. A preprocessor macro matching `<PREFIX>_COMPILER_IS_<compiler>` is generated for each compiler known to CMake to contain the value `0` or `1`.
Possible compiler identifiers are documented with the [`CMAKE_<LANG>_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") variable. Available features in this version of CMake are listed in the [`CMAKE_C_KNOWN_FEATURES`](../prop_gbl/cmake_c_known_features#prop_gbl:CMAKE_C_KNOWN_FEATURES "CMAKE_C_KNOWN_FEATURES") and [`CMAKE_CXX_KNOWN_FEATURES`](../prop_gbl/cmake_cxx_known_features#prop_gbl:CMAKE_CXX_KNOWN_FEATURES "CMAKE_CXX_KNOWN_FEATURES") global properties. The `{c,cxx}_std_*` meta-features are ignored if requested.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features.
`ALLOW_UNKNOWN_COMPILERS` and `ALLOW_UNKNOWN_COMPILER_VERSIONS` cause the module to generate conditions that treat unknown compilers as simply lacking all features. Without these options the default behavior is to generate a `#error` for unknown compilers.
Feature Test Macros
-------------------
For each compiler, a preprocessor macro is generated matching `<PREFIX>_COMPILER_IS_<compiler>` which has the content either `0` or `1`, depending on the compiler in use. Preprocessor macros for compiler version components are generated matching `<PREFIX>_COMPILER_VERSION_MAJOR` `<PREFIX>_COMPILER_VERSION_MINOR` and `<PREFIX>_COMPILER_VERSION_PATCH` containing decimal values for the corresponding compiler version components, if defined.
A preprocessor test is generated based on the compiler version denoting whether each feature is enabled. A preprocessor macro matching `<PREFIX>_COMPILER_<FEATURE>`, where `<FEATURE>` is the upper-case `<feature>` name, is generated to contain the value `0` or `1` depending on whether the compiler in use supports the feature:
```
write_compiler_detection_header(
FILE climbingstats_compiler_detection.h
PREFIX ClimbingStats
COMPILERS GNU Clang AppleClang MSVC Intel
FEATURES cxx_variadic_templates
)
```
```
#if ClimbingStats_COMPILER_CXX_VARIADIC_TEMPLATES
template<typename... T>
void someInterface(T t...) { /* ... */ }
#else
// Compatibility versions
template<typename T1>
void someInterface(T1 t1) { /* ... */ }
template<typename T1, typename T2>
void someInterface(T1 t1, T2 t2) { /* ... */ }
template<typename T1, typename T2, typename T3>
void someInterface(T1 t1, T2 t2, T3 t3) { /* ... */ }
#endif
```
Symbol Macros
-------------
Some additional symbol-defines are created for particular features for use as symbols which may be conditionally defined empty:
```
class MyClass ClimbingStats_FINAL
{
ClimbingStats_CONSTEXPR int someInterface() { return 42; }
};
```
The `ClimbingStats_FINAL` macro will expand to `final` if the compiler (and its flags) support the `cxx_final` feature, and the `ClimbingStats_CONSTEXPR` macro will expand to `constexpr` if `cxx_constexpr` is supported.
The following features generate corresponding symbol defines:
| Feature | Define | Symbol |
| --- | --- | --- |
| `c_restrict` | `<PREFIX>_RESTRICT` | `restrict` |
| `cxx_constexpr` | `<PREFIX>_CONSTEXPR` | `constexpr` |
| `cxx_deleted_functions` | `<PREFIX>_DELETED_FUNCTION` | `= delete` |
| `cxx_extern_templates` | `<PREFIX>_EXTERN_TEMPLATE` | `extern` |
| `cxx_final` | `<PREFIX>_FINAL` | `final` |
| `cxx_noexcept` | `<PREFIX>_NOEXCEPT` | `noexcept` |
| `cxx_noexcept` | `<PREFIX>_NOEXCEPT_EXPR(X)` | `noexcept(X)` |
| `cxx_override` | `<PREFIX>_OVERRIDE` | `override` |
Compatibility Implementation Macros
-----------------------------------
Some features are suitable for wrapping in a macro with a backward compatibility implementation if the compiler does not support the feature.
When the `cxx_static_assert` feature is not provided by the compiler, a compatibility implementation is available via the `<PREFIX>_STATIC_ASSERT(COND)` and `<PREFIX>_STATIC_ASSERT_MSG(COND, MSG)` function-like macros. The macros expand to `static_assert` where that compiler feature is available, and to a compatibility implementation otherwise. In the first form, the condition is stringified in the message field of `static_assert`. In the second form, the message `MSG` is passed to the message field of `static_assert`, or ignored if using the backward compatibility implementation.
The `cxx_attribute_deprecated` feature provides a macro definition `<PREFIX>_DEPRECATED`, which expands to either the standard `[[deprecated]]` attribute or a compiler-specific decorator such as `__attribute__((__deprecated__))` used by GNU compilers.
The `cxx_alignas` feature provides a macro definition `<PREFIX>_ALIGNAS` which expands to either the standard `alignas` decorator or a compiler-specific decorator such as `__attribute__ ((__aligned__))` used by GNU compilers.
The `cxx_alignof` feature provides a macro definition `<PREFIX>_ALIGNOF` which expands to either the standard `alignof` decorator or a compiler-specific decorator such as `__alignof__` used by GNU compilers.
| Feature | Define | Symbol |
| --- | --- | --- |
| `cxx_alignas` | `<PREFIX>_ALIGNAS` | `alignas` |
| `cxx_alignof` | `<PREFIX>_ALIGNOF` | `alignof` |
| `cxx_nullptr` | `<PREFIX>_NULLPTR` | `nullptr` |
| `cxx_static_assert` | `<PREFIX>_STATIC_ASSERT` | `static_assert` |
| `cxx_static_assert` | `<PREFIX>_STATIC_ASSERT_MSG` | `static_assert` |
| `cxx_attribute_deprecated` | `<PREFIX>_DEPRECATED` | `[[deprecated]]` |
| `cxx_attribute_deprecated` | `<PREFIX>_DEPRECATED_MSG` | `[[deprecated]]` |
| `cxx_thread_local` | `<PREFIX>_THREAD_LOCAL` | `thread_local` |
A use-case which arises with such deprecation macros is the deprecation of an entire library. In that case, all public API in the library may be decorated with the `<PREFIX>_DEPRECATED` macro. This results in very noisy build output when building the library itself, so the macro may be may be defined to empty in that case when building the deprecated library:
```
add_library(compat_support ${srcs})
target_compile_definitions(compat_support
PRIVATE
CompatSupport_DEPRECATED=
)
```
cmake CMakeForceCompiler CMakeForceCompiler
==================
Deprecated. Do not use.
The macros provided by this module were once intended for use by cross-compiling toolchain files when CMake was not able to automatically detect the compiler identification. Since the introduction of this module, CMake’s compiler identification capabilities have improved and can now be taught to recognize any compiler. Furthermore, the suite of information CMake detects from a compiler is now too extensive to be provided by toolchain files using these macros.
One common use case for this module was to skip CMake’s checks for a working compiler when using a cross-compiler that cannot link binaries without special flags or custom linker scripts. This case is now supported by setting the [`CMAKE_TRY_COMPILE_TARGET_TYPE`](../variable/cmake_try_compile_target_type#variable:CMAKE_TRY_COMPILE_TARGET_TYPE "CMAKE_TRY_COMPILE_TARGET_TYPE") variable in the toolchain file instead.
Macro CMAKE\_FORCE\_C\_COMPILER has the following signature:
```
CMAKE_FORCE_C_COMPILER(<compiler> <compiler-id>)
```
It sets CMAKE\_C\_COMPILER to the given compiler and the cmake internal variable CMAKE\_C\_COMPILER\_ID to the given compiler-id. It also bypasses the check for working compiler and basic compiler information tests.
Macro CMAKE\_FORCE\_CXX\_COMPILER has the following signature:
```
CMAKE_FORCE_CXX_COMPILER(<compiler> <compiler-id>)
```
It sets CMAKE\_CXX\_COMPILER to the given compiler and the cmake internal variable CMAKE\_CXX\_COMPILER\_ID to the given compiler-id. It also bypasses the check for working compiler and basic compiler information tests.
Macro CMAKE\_FORCE\_Fortran\_COMPILER has the following signature:
```
CMAKE_FORCE_Fortran_COMPILER(<compiler> <compiler-id>)
```
It sets CMAKE\_Fortran\_COMPILER to the given compiler and the cmake internal variable CMAKE\_Fortran\_COMPILER\_ID to the given compiler-id. It also bypasses the check for working compiler and basic compiler information tests.
So a simple toolchain file could look like this:
```
include (CMakeForceCompiler)
set(CMAKE_SYSTEM_NAME Generic)
CMAKE_FORCE_C_COMPILER (chc12 MetrowerksHicross)
CMAKE_FORCE_CXX_COMPILER (chc12 MetrowerksHicross)
```
cmake FindVulkan FindVulkan
==========
Try to find Vulkan
IMPORTED Targets
----------------
This module defines [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target `Vulkan::Vulkan`, if Vulkan has been found.
Result Variables
----------------
This module defines the following variables:
```
Vulkan_FOUND - True if Vulkan was found
Vulkan_INCLUDE_DIRS - include directories for Vulkan
Vulkan_LIBRARIES - link against this library to use Vulkan
```
The module will also define two cache variables:
```
Vulkan_INCLUDE_DIR - the Vulkan include directory
Vulkan_LIBRARY - the path to the Vulkan library
```
cmake CheckLibraryExists CheckLibraryExists
==================
Check if the function exists.
CHECK\_LIBRARY\_EXISTS (LIBRARY FUNCTION LOCATION VARIABLE)
```
LIBRARY - the name of the library you are looking for
FUNCTION - the name of the function
LOCATION - location where the library should be found
VARIABLE - variable to store the result
Will be created as an internal cache variable.
```
The following variables may be set before calling this macro to modify the way the check is run:
```
CMAKE_REQUIRED_FLAGS = string of compile command line flags
CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
CMAKE_REQUIRED_QUIET = execute quietly without messages
```
cmake FindCoin3D FindCoin3D
==========
Find Coin3D (Open Inventor)
Coin3D is an implementation of the Open Inventor API. It provides data structures and algorithms for 3D visualization.
This module defines the following variables
```
COIN3D_FOUND - system has Coin3D - Open Inventor
COIN3D_INCLUDE_DIRS - where the Inventor include directory can be found
COIN3D_LIBRARIES - Link to this to use Coin3D
```
cmake FindCUDA FindCUDA
========
Tools for building CUDA C files: libraries and build dependencies.
This script locates the NVIDIA CUDA C tools. It should work on linux, windows, and mac and should be reasonably up to date with CUDA C releases.
This script makes use of the standard find\_package arguments of <VERSION>, REQUIRED and QUIET. CUDA\_FOUND will report if an acceptable version of CUDA was found.
The script will prompt the user to specify CUDA\_TOOLKIT\_ROOT\_DIR if the prefix cannot be determined by the location of nvcc in the system path and REQUIRED is specified to find\_package(). To use a different installed version of the toolkit set the environment variable CUDA\_BIN\_PATH before running cmake (e.g. CUDA\_BIN\_PATH=/usr/local/cuda1.0 instead of the default /usr/local/cuda) or set CUDA\_TOOLKIT\_ROOT\_DIR after configuring. If you change the value of CUDA\_TOOLKIT\_ROOT\_DIR, various components that depend on the path will be relocated.
It might be necessary to set CUDA\_TOOLKIT\_ROOT\_DIR manually on certain platforms, or to use a cuda runtime not installed in the default location. In newer versions of the toolkit the cuda library is included with the graphics driver- be sure that the driver version matches what is needed by the cuda runtime version.
The following variables affect the behavior of the macros in the script (in alphebetical order). Note that any of these flags can be changed multiple times in the same directory before calling CUDA\_ADD\_EXECUTABLE, CUDA\_ADD\_LIBRARY, CUDA\_COMPILE, CUDA\_COMPILE\_PTX, CUDA\_COMPILE\_FATBIN, CUDA\_COMPILE\_CUBIN or CUDA\_WRAP\_SRCS:
```
CUDA_64_BIT_DEVICE_CODE (Default matches host bit size)
-- Set to ON to compile for 64 bit device code, OFF for 32 bit device code.
Note that making this different from the host code when generating object
or C files from CUDA code just won't work, because size_t gets defined by
nvcc in the generated source. If you compile to PTX and then load the
file yourself, you can mix bit sizes between device and host.
CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE (Default ON)
-- Set to ON if you want the custom build rule to be attached to the source
file in Visual Studio. Turn OFF if you add the same cuda file to multiple
targets.
This allows the user to build the target from the CUDA file; however, bad
things can happen if the CUDA source file is added to multiple targets.
When performing parallel builds it is possible for the custom build
command to be run more than once and in parallel causing cryptic build
errors. VS runs the rules for every source file in the target, and a
source can have only one rule no matter how many projects it is added to.
When the rule is run from multiple targets race conditions can occur on
the generated file. Eventually everything will get built, but if the user
is unaware of this behavior, there may be confusion. It would be nice if
this script could detect the reuse of source files across multiple targets
and turn the option off for the user, but no good solution could be found.
CUDA_BUILD_CUBIN (Default OFF)
-- Set to ON to enable and extra compilation pass with the -cubin option in
Device mode. The output is parsed and register, shared memory usage is
printed during build.
CUDA_BUILD_EMULATION (Default OFF for device mode)
-- Set to ON for Emulation mode. -D_DEVICEEMU is defined for CUDA C files
when CUDA_BUILD_EMULATION is TRUE.
CUDA_LINK_LIBRARIES_KEYWORD (Default "")
-- The <PRIVATE|PUBLIC|INTERFACE> keyword to use for internal
target_link_libraries calls. The default is to use no keyword which
uses the old "plain" form of target_link_libraries. Note that is matters
because whatever is used inside the FindCUDA module must also be used
outside - the two forms of target_link_libraries cannot be mixed.
CUDA_GENERATED_OUTPUT_DIR (Default CMAKE_CURRENT_BINARY_DIR)
-- Set to the path you wish to have the generated files placed. If it is
blank output files will be placed in CMAKE_CURRENT_BINARY_DIR.
Intermediate files will always be placed in
CMAKE_CURRENT_BINARY_DIR/CMakeFiles.
CUDA_HOST_COMPILATION_CPP (Default ON)
-- Set to OFF for C compilation of host code.
CUDA_HOST_COMPILER (Default CMAKE_C_COMPILER, $(VCInstallDir)/bin for VS)
-- Set the host compiler to be used by nvcc. Ignored if -ccbin or
--compiler-bindir is already present in the CUDA_NVCC_FLAGS or
CUDA_NVCC_FLAGS_<CONFIG> variables. For Visual Studio targets
$(VCInstallDir)/bin is a special value that expands out to the path when
the command is run from within VS.
CUDA_NVCC_FLAGS
CUDA_NVCC_FLAGS_<CONFIG>
-- Additional NVCC command line arguments. NOTE: multiple arguments must be
semi-colon delimited (e.g. --compiler-options;-Wall)
CUDA_PROPAGATE_HOST_FLAGS (Default ON)
-- Set to ON to propagate CMAKE_{C,CXX}_FLAGS and their configuration
dependent counterparts (e.g. CMAKE_C_FLAGS_DEBUG) automatically to the
host compiler through nvcc's -Xcompiler flag. This helps make the
generated host code match the rest of the system better. Sometimes
certain flags give nvcc problems, and this will help you turn the flag
propagation off. This does not affect the flags supplied directly to nvcc
via CUDA_NVCC_FLAGS or through the OPTION flags specified through
CUDA_ADD_LIBRARY, CUDA_ADD_EXECUTABLE, or CUDA_WRAP_SRCS. Flags used for
shared library compilation are not affected by this flag.
CUDA_SEPARABLE_COMPILATION (Default OFF)
-- If set this will enable separable compilation for all CUDA runtime object
files. If used outside of CUDA_ADD_EXECUTABLE and CUDA_ADD_LIBRARY
(e.g. calling CUDA_WRAP_SRCS directly),
CUDA_COMPUTE_SEPARABLE_COMPILATION_OBJECT_FILE_NAME and
CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS should be called.
CUDA_SOURCE_PROPERTY_FORMAT
-- If this source file property is set, it can override the format specified
to CUDA_WRAP_SRCS (OBJ, PTX, CUBIN, or FATBIN). If an input source file
is not a .cu file, setting this file will cause it to be treated as a .cu
file. See documentation for set_source_files_properties on how to set
this property.
CUDA_USE_STATIC_CUDA_RUNTIME (Default ON)
-- When enabled the static version of the CUDA runtime library will be used
in CUDA_LIBRARIES. If the version of CUDA configured doesn't support
this option, then it will be silently disabled.
CUDA_VERBOSE_BUILD (Default OFF)
-- Set to ON to see all the commands used when building the CUDA file. When
using a Makefile generator the value defaults to VERBOSE (run make
VERBOSE=1 to see output), although setting CUDA_VERBOSE_BUILD to ON will
always print the output.
```
The script creates the following macros (in alphebetical order):
```
CUDA_ADD_CUFFT_TO_TARGET( cuda_target )
-- Adds the cufft library to the target (can be any target). Handles whether
you are in emulation mode or not.
CUDA_ADD_CUBLAS_TO_TARGET( cuda_target )
-- Adds the cublas library to the target (can be any target). Handles
whether you are in emulation mode or not.
CUDA_ADD_EXECUTABLE( cuda_target file0 file1 ...
[WIN32] [MACOSX_BUNDLE] [EXCLUDE_FROM_ALL] [OPTIONS ...] )
-- Creates an executable "cuda_target" which is made up of the files
specified. All of the non CUDA C files are compiled using the standard
build rules specified by CMAKE and the cuda files are compiled to object
files using nvcc and the host compiler. In addition CUDA_INCLUDE_DIRS is
added automatically to include_directories(). Some standard CMake target
calls can be used on the target after calling this macro
(e.g. set_target_properties and target_link_libraries), but setting
properties that adjust compilation flags will not affect code compiled by
nvcc. Such flags should be modified before calling CUDA_ADD_EXECUTABLE,
CUDA_ADD_LIBRARY or CUDA_WRAP_SRCS.
CUDA_ADD_LIBRARY( cuda_target file0 file1 ...
[STATIC | SHARED | MODULE] [EXCLUDE_FROM_ALL] [OPTIONS ...] )
-- Same as CUDA_ADD_EXECUTABLE except that a library is created.
CUDA_BUILD_CLEAN_TARGET()
-- Creates a convience target that deletes all the dependency files
generated. You should make clean after running this target to ensure the
dependency files get regenerated.
CUDA_COMPILE( generated_files file0 file1 ... [STATIC | SHARED | MODULE]
[OPTIONS ...] )
-- Returns a list of generated files from the input source files to be used
with ADD_LIBRARY or ADD_EXECUTABLE.
CUDA_COMPILE_PTX( generated_files file0 file1 ... [OPTIONS ...] )
-- Returns a list of PTX files generated from the input source files.
CUDA_COMPILE_FATBIN( generated_files file0 file1 ... [OPTIONS ...] )
-- Returns a list of FATBIN files generated from the input source files.
CUDA_COMPILE_CUBIN( generated_files file0 file1 ... [OPTIONS ...] )
-- Returns a list of CUBIN files generated from the input source files.
CUDA_COMPUTE_SEPARABLE_COMPILATION_OBJECT_FILE_NAME( output_file_var
cuda_target
object_files )
-- Compute the name of the intermediate link file used for separable
compilation. This file name is typically passed into
CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS. output_file_var is produced
based on cuda_target the list of objects files that need separable
compilation as specified by object_files. If the object_files list is
empty, then output_file_var will be empty. This function is called
automatically for CUDA_ADD_LIBRARY and CUDA_ADD_EXECUTABLE. Note that
this is a function and not a macro.
CUDA_INCLUDE_DIRECTORIES( path0 path1 ... )
-- Sets the directories that should be passed to nvcc
(e.g. nvcc -Ipath0 -Ipath1 ... ). These paths usually contain other .cu
files.
CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS( output_file_var cuda_target
nvcc_flags object_files)
-- Generates the link object required by separable compilation from the given
object files. This is called automatically for CUDA_ADD_EXECUTABLE and
CUDA_ADD_LIBRARY, but can be called manually when using CUDA_WRAP_SRCS
directly. When called from CUDA_ADD_LIBRARY or CUDA_ADD_EXECUTABLE the
nvcc_flags passed in are the same as the flags passed in via the OPTIONS
argument. The only nvcc flag added automatically is the bitness flag as
specified by CUDA_64_BIT_DEVICE_CODE. Note that this is a function
instead of a macro.
CUDA_SELECT_NVCC_ARCH_FLAGS(out_variable [target_CUDA_architectures])
-- Selects GPU arch flags for nvcc based on target_CUDA_architectures
target_CUDA_architectures : Auto | Common | All | LIST(ARCH_AND_PTX ...)
- "Auto" detects local machine GPU compute arch at runtime.
- "Common" and "All" cover common and entire subsets of architectures
ARCH_AND_PTX : NAME | NUM.NUM | NUM.NUM(NUM.NUM) | NUM.NUM+PTX
NAME: Fermi Kepler Maxwell Kepler+Tegra Kepler+Tesla Maxwell+Tegra Pascal
NUM: Any number. Only those pairs are currently accepted by NVCC though:
2.0 2.1 3.0 3.2 3.5 3.7 5.0 5.2 5.3 6.0 6.2
Returns LIST of flags to be added to CUDA_NVCC_FLAGS in ${out_variable}
Additionally, sets ${out_variable}_readable to the resulting numeric list
Example:
CUDA_SELECT_NVCC_ARCH_FLAGS(ARCH_FLAGS 3.0 3.5+PTX 5.2(5.0) Maxwell)
LIST(APPEND CUDA_NVCC_FLAGS ${ARCH_FLAGS})
More info on CUDA architectures: https://en.wikipedia.org/wiki/CUDA
Note that this is a function instead of a macro.
CUDA_WRAP_SRCS ( cuda_target format generated_files file0 file1 ...
[STATIC | SHARED | MODULE] [OPTIONS ...] )
-- This is where all the magic happens. CUDA_ADD_EXECUTABLE,
CUDA_ADD_LIBRARY, CUDA_COMPILE, and CUDA_COMPILE_PTX all call this
function under the hood.
Given the list of files (file0 file1 ... fileN) this macro generates
custom commands that generate either PTX or linkable objects (use "PTX" or
"OBJ" for the format argument to switch). Files that don't end with .cu
or have the HEADER_FILE_ONLY property are ignored.
The arguments passed in after OPTIONS are extra command line options to
give to nvcc. You can also specify per configuration options by
specifying the name of the configuration followed by the options. General
options must precede configuration specific options. Not all
configurations need to be specified, only the ones provided will be used.
OPTIONS -DFLAG=2 "-DFLAG_OTHER=space in flag"
DEBUG -g
RELEASE --use_fast_math
RELWITHDEBINFO --use_fast_math;-g
MINSIZEREL --use_fast_math
For certain configurations (namely VS generating object files with
CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE set to ON), no generated file will
be produced for the given cuda file. This is because when you add the
cuda file to Visual Studio it knows that this file produces an object file
and will link in the resulting object file automatically.
This script will also generate a separate cmake script that is used at
build time to invoke nvcc. This is for several reasons.
1. nvcc can return negative numbers as return values which confuses
Visual Studio into thinking that the command succeeded. The script now
checks the error codes and produces errors when there was a problem.
2. nvcc has been known to not delete incomplete results when it
encounters problems. This confuses build systems into thinking the
target was generated when in fact an unusable file exists. The script
now deletes the output files if there was an error.
3. By putting all the options that affect the build into a file and then
make the build rule dependent on the file, the output files will be
regenerated when the options change.
This script also looks at optional arguments STATIC, SHARED, or MODULE to
determine when to target the object compilation for a shared library.
BUILD_SHARED_LIBS is ignored in CUDA_WRAP_SRCS, but it is respected in
CUDA_ADD_LIBRARY. On some systems special flags are added for building
objects intended for shared libraries. A preprocessor macro,
<target_name>_EXPORTS is defined when a shared library compilation is
detected.
Flags passed into add_definitions with -D or /D are passed along to nvcc.
```
The script defines the following variables:
```
CUDA_VERSION_MAJOR -- The major version of cuda as reported by nvcc.
CUDA_VERSION_MINOR -- The minor version.
CUDA_VERSION
CUDA_VERSION_STRING -- CUDA_VERSION_MAJOR.CUDA_VERSION_MINOR
CUDA_HAS_FP16 -- Whether a short float (float16,fp16) is supported.
CUDA_TOOLKIT_ROOT_DIR -- Path to the CUDA Toolkit (defined if not set).
CUDA_SDK_ROOT_DIR -- Path to the CUDA SDK. Use this to find files in the
SDK. This script will not directly support finding
specific libraries or headers, as that isn't
supported by NVIDIA. If you want to change
libraries when the path changes see the
FindCUDA.cmake script for an example of how to clear
these variables. There are also examples of how to
use the CUDA_SDK_ROOT_DIR to locate headers or
libraries, if you so choose (at your own risk).
CUDA_INCLUDE_DIRS -- Include directory for cuda headers. Added automatically
for CUDA_ADD_EXECUTABLE and CUDA_ADD_LIBRARY.
CUDA_LIBRARIES -- Cuda RT library.
CUDA_CUFFT_LIBRARIES -- Device or emulation library for the Cuda FFT
implementation (alternative to:
CUDA_ADD_CUFFT_TO_TARGET macro)
CUDA_CUBLAS_LIBRARIES -- Device or emulation library for the Cuda BLAS
implementation (alternative to:
CUDA_ADD_CUBLAS_TO_TARGET macro).
CUDA_cudart_static_LIBRARY -- Statically linkable cuda runtime library.
Only available for CUDA version 5.5+
CUDA_cudadevrt_LIBRARY -- Device runtime library.
Required for separable compilation.
CUDA_cupti_LIBRARY -- CUDA Profiling Tools Interface library.
Only available for CUDA version 4.0+.
CUDA_curand_LIBRARY -- CUDA Random Number Generation library.
Only available for CUDA version 3.2+.
CUDA_cusolver_LIBRARY -- CUDA Direct Solver library.
Only available for CUDA version 7.0+.
CUDA_cusparse_LIBRARY -- CUDA Sparse Matrix library.
Only available for CUDA version 3.2+.
CUDA_npp_LIBRARY -- NVIDIA Performance Primitives lib.
Only available for CUDA version 4.0+.
CUDA_nppc_LIBRARY -- NVIDIA Performance Primitives lib (core).
Only available for CUDA version 5.5+.
CUDA_nppi_LIBRARY -- NVIDIA Performance Primitives lib (image processing).
Only available for CUDA version 5.5+.
CUDA_npps_LIBRARY -- NVIDIA Performance Primitives lib (signal processing).
Only available for CUDA version 5.5+.
CUDA_nvcuvenc_LIBRARY -- CUDA Video Encoder library.
Only available for CUDA version 3.2+.
Windows only.
CUDA_nvcuvid_LIBRARY -- CUDA Video Decoder library.
Only available for CUDA version 3.2+.
Windows only.
```
| programming_docs |
cmake CMakeFindPackageMode CMakeFindPackageMode
====================
This file is executed by cmake when invoked with –find-package. It expects that the following variables are set using -D:
`NAME` name of the package
`COMPILER_ID` the CMake compiler ID for which the result is, i.e. GNU/Intel/Clang/MSVC, etc.
`LANGUAGE` language for which the result will be used, i.e. C/CXX/Fortan/ASM
`MODE`
`EXIST` only check for existence of the given package
`COMPILE` print the flags needed for compiling an object file which uses the given package
`LINK` print the flags needed for linking when using the given package
`QUIET` if TRUE, don’t print anything
cmake FindALSA FindALSA
========
Find alsa
Find the alsa libraries (asound)
```
This module defines the following variables:
ALSA_FOUND - True if ALSA_INCLUDE_DIR & ALSA_LIBRARY are found
ALSA_LIBRARIES - Set when ALSA_LIBRARY is found
ALSA_INCLUDE_DIRS - Set when ALSA_INCLUDE_DIR is found
```
```
ALSA_INCLUDE_DIR - where to find asoundlib.h, etc.
ALSA_LIBRARY - the asound library
ALSA_VERSION_STRING - the version of alsa found (since CMake 2.8.8)
```
cmake FindwxWindows FindwxWindows
=============
Find wxWindows (wxWidgets) installation
This module finds if wxWindows/wxWidgets is installed and determines where the include files and libraries are. It also determines what the name of the library is. Please note this file is DEPRECATED and replaced by FindwxWidgets.cmake. This code sets the following variables:
```
WXWINDOWS_FOUND = system has WxWindows
WXWINDOWS_LIBRARIES = path to the wxWindows libraries
on Unix/Linux with additional
linker flags from
"wx-config --libs"
CMAKE_WXWINDOWS_CXX_FLAGS = Compiler flags for wxWindows,
essentially "`wx-config --cxxflags`"
on Linux
WXWINDOWS_INCLUDE_DIR = where to find "wx/wx.h" and "wx/setup.h"
WXWINDOWS_LINK_DIRECTORIES = link directories, useful for rpath on
Unix
WXWINDOWS_DEFINITIONS = extra defines
```
OPTIONS If you need OpenGL support please
```
set(WXWINDOWS_USE_GL 1)
```
in your CMakeLists.txt *before* you include this file.
```
HAVE_ISYSTEM - true required to replace -I by -isystem on g++
```
For convenience include Use\_wxWindows.cmake in your project’s CMakeLists.txt using include(${CMAKE\_CURRENT\_LIST\_DIR}/Use\_wxWindows.cmake).
USAGE
```
set(WXWINDOWS_USE_GL 1)
find_package(wxWindows)
```
NOTES wxWidgets 2.6.x is supported for monolithic builds e.g. compiled in wx/build/msw dir as:
```
nmake -f makefile.vc BUILD=debug SHARED=0 USE_OPENGL=1 MONOLITHIC=1
```
DEPRECATED
```
CMAKE_WX_CAN_COMPILE
WXWINDOWS_LIBRARY
CMAKE_WX_CXX_FLAGS
WXWINDOWS_INCLUDE_PATH
```
AUTHOR Jan Woetzel <<http://www.mip.informatik.uni-kiel.de/~jw>> (07/2003-01/2006)
cmake FindosgAnimation FindosgAnimation
================
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgAnimation This module defines
OSGANIMATION\_FOUND - Was osgAnimation found? OSGANIMATION\_INCLUDE\_DIR - Where to find the headers OSGANIMATION\_LIBRARIES - The libraries to link against for the OSG (use this)
OSGANIMATION\_LIBRARY - The OSG library OSGANIMATION\_LIBRARY\_DEBUG - The OSG debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake FindFLTK2 FindFLTK2
=========
Find the native FLTK2 includes and library
The following settings are defined
```
FLTK2_FLUID_EXECUTABLE, where to find the Fluid tool
FLTK2_WRAP_UI, This enables the FLTK2_WRAP_UI command
FLTK2_INCLUDE_DIR, where to find include files
FLTK2_LIBRARIES, list of fltk2 libraries
FLTK2_FOUND, Don't use FLTK2 if false.
```
The following settings should not be used in general.
```
FLTK2_BASE_LIBRARY = the full path to fltk2.lib
FLTK2_GL_LIBRARY = the full path to fltk2_gl.lib
FLTK2_IMAGES_LIBRARY = the full path to fltk2_images.lib
```
cmake FindBacktrace FindBacktrace
=============
Find provider for backtrace(3).
Checks if OS supports backtrace(3) via either libc or custom library. This module defines the following variables:
`Backtrace_HEADER` The header file needed for backtrace(3). Cached. Could be forcibly set by user.
`Backtrace_INCLUDE_DIRS` The include directories needed to use backtrace(3) header.
`Backtrace_LIBRARIES` The libraries (linker flags) needed to use backtrace(3), if any.
`Backtrace_FOUND` Is set if and only if backtrace(3) support detected. The following cache variables are also available to set or use:
`Backtrace_LIBRARY` The external library providing backtrace, if any.
`Backtrace_INCLUDE_DIR` The directory holding the backtrace(3) header. Typical usage is to generate of header file using configure\_file() with the contents like the following:
```
#cmakedefine01 Backtrace_FOUND
#if Backtrace_FOUND
# include <${Backtrace_HEADER}>
#endif
```
And then reference that generated header file in actual source.
cmake FindTclStub FindTclStub
===========
TCL\_STUB\_LIBRARY\_DEBUG and TK\_STUB\_LIBRARY\_DEBUG were removed.
This module finds Tcl stub libraries. It first finds Tcl include files and libraries by calling FindTCL.cmake. How to Use the Tcl Stubs Library:
```
http://tcl.activestate.com/doc/howto/stubs.html
```
Using Stub Libraries:
```
http://safari.oreilly.com/0130385603/ch48lev1sec3
```
This code sets the following variables:
```
TCL_STUB_LIBRARY = path to Tcl stub library
TK_STUB_LIBRARY = path to Tk stub library
TTK_STUB_LIBRARY = path to ttk stub library
```
In an effort to remove some clutter and clear up some issues for people who are not necessarily Tcl/Tk gurus/developpers, some variables were moved or removed. Changes compared to CMake 2.4 are:
```
=> these libs are not packaged by default with Tcl/Tk distributions.
Even when Tcl/Tk is built from source, several flavors of debug libs
are created and there is no real reason to pick a single one
specifically (say, amongst tclstub84g, tclstub84gs, or tclstub84sgx).
Let's leave that choice to the user by allowing him to assign
TCL_STUB_LIBRARY to any Tcl library, debug or not.
```
cmake DeployQt4 DeployQt4
=========
Functions to help assemble a standalone Qt4 executable.
A collection of CMake utility functions useful for deploying Qt4 executables.
The following functions are provided by this module:
```
write_qt4_conf
resolve_qt4_paths
fixup_qt4_executable
install_qt4_plugin_path
install_qt4_plugin
install_qt4_executable
```
Requires CMake 2.6 or greater because it uses function and PARENT\_SCOPE. Also depends on BundleUtilities.cmake.
```
WRITE_QT4_CONF(<qt_conf_dir> <qt_conf_contents>)
```
Writes a qt.conf file with the <qt\_conf\_contents> into <qt\_conf\_dir>.
```
RESOLVE_QT4_PATHS(<paths_var> [<executable_path>])
```
Loop through <paths\_var> list and if any don’t exist resolve them relative to the <executable\_path> (if supplied) or the CMAKE\_INSTALL\_PREFIX.
```
FIXUP_QT4_EXECUTABLE(<executable>
[<qtplugins> <libs> <dirs> <plugins_dir> <request_qt_conf>])
```
Copies Qt plugins, writes a Qt configuration file (if needed) and fixes up a Qt4 executable using BundleUtilities so it is standalone and can be drag-and-drop copied to another machine as long as all of the system libraries are compatible.
<executable> should point to the executable to be fixed-up.
<qtplugins> should contain a list of the names or paths of any Qt plugins to be installed.
<libs> will be passed to BundleUtilities and should be a list of any already installed plugins, libraries or executables to also be fixed-up.
<dirs> will be passed to BundleUtilities and should contain and directories to be searched to find library dependencies.
<plugins\_dir> allows an custom plugins directory to be used.
<request\_qt\_conf> will force a qt.conf file to be written even if not needed.
```
INSTALL_QT4_PLUGIN_PATH(plugin executable copy installed_plugin_path_var
<plugins_dir> <component> <configurations>)
```
Install (or copy) a resolved <plugin> to the default plugins directory (or <plugins\_dir>) relative to <executable> and store the result in <installed\_plugin\_path\_var>.
If <copy> is set to TRUE then the plugins will be copied rather than installed. This is to allow this module to be used at CMake time rather than install time.
If <component> is set then anything installed will use this COMPONENT.
```
INSTALL_QT4_PLUGIN(plugin executable copy installed_plugin_path_var
<plugins_dir> <component>)
```
Install (or copy) an unresolved <plugin> to the default plugins directory (or <plugins\_dir>) relative to <executable> and store the result in <installed\_plugin\_path\_var>. See documentation of INSTALL\_QT4\_PLUGIN\_PATH.
```
INSTALL_QT4_EXECUTABLE(<executable>
[<qtplugins> <libs> <dirs> <plugins_dir> <request_qt_conf> <component>])
```
Installs Qt plugins, writes a Qt configuration file (if needed) and fixes up a Qt4 executable using BundleUtilities so it is standalone and can be drag-and-drop copied to another machine as long as all of the system libraries are compatible. The executable will be fixed-up at install time. <component> is the COMPONENT used for bundle fixup and plugin installation. See documentation of FIXUP\_QT4\_BUNDLE.
cmake FindMPEG2 FindMPEG2
=========
Find the native MPEG2 includes and library
This module defines
```
MPEG2_INCLUDE_DIR, path to mpeg2dec/mpeg2.h, etc.
MPEG2_LIBRARIES, the libraries required to use MPEG2.
MPEG2_FOUND, If false, do not try to use MPEG2.
```
also defined, but not for general use are
```
MPEG2_mpeg2_LIBRARY, where to find the MPEG2 library.
MPEG2_vo_LIBRARY, where to find the vo library.
```
cmake CTest CTest
=====
Configure a project for testing with CTest/CDash
Include this module in the top CMakeLists.txt file of a project to enable testing with CTest and dashboard submissions to CDash:
```
project(MyProject)
...
include(CTest)
```
The module automatically creates a `BUILD_TESTING` option that selects whether to enable testing support (`ON` by default). After including the module, use code like:
```
if(BUILD_TESTING)
# ... CMake code to create tests ...
endif()
```
to creating tests when testing is enabled.
To enable submissions to a CDash server, create a `CTestConfig.cmake` file at the top of the project with content such as:
```
set(CTEST_PROJECT_NAME "MyProject")
set(CTEST_NIGHTLY_START_TIME "01:00:00 UTC")
set(CTEST_DROP_METHOD "http")
set(CTEST_DROP_SITE "my.cdash.org")
set(CTEST_DROP_LOCATION "/submit.php?project=MyProject")
set(CTEST_DROP_SITE_CDASH TRUE)
```
(the CDash server can provide the file to a project administrator who configures `MyProject`). Settings in the config file are shared by both this `CTest` module and the [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") command-line [Dashboard Client](../manual/ctest.1#dashboard-client) mode (`ctest -S`).
While building a project for submission to CDash, CTest scans the build output for errors and warnings and reports them with surrounding context from the build log. This generic approach works for all build tools, but does not give details about the command invocation that produced a given problem. One may get more detailed reports by setting the [`CTEST_USE_LAUNCHERS`](../variable/ctest_use_launchers#variable:CTEST_USE_LAUNCHERS "CTEST_USE_LAUNCHERS") variable:
```
set(CTEST_USE_LAUNCHERS 1)
```
in the `CTestConfig.cmake` file.
cmake CheckLanguage CheckLanguage
=============
Check if a language can be enabled
Usage:
```
check_language(<lang>)
```
where <lang> is a language that may be passed to enable\_language() such as “Fortran”. If CMAKE\_<lang>\_COMPILER is already defined the check does nothing. Otherwise it tries enabling the language in a test project. The result is cached in CMAKE\_<lang>\_COMPILER as the compiler that was found, or NOTFOUND if the language cannot be enabled.
Example:
```
check_language(Fortran)
if(CMAKE_Fortran_COMPILER)
enable_language(Fortran)
else()
message(STATUS "No Fortran support")
endif()
```
cmake FindQuickTime FindQuickTime
=============
Locate QuickTime This module defines QUICKTIME\_LIBRARY QUICKTIME\_FOUND, if false, do not try to link to gdal QUICKTIME\_INCLUDE\_DIR, where to find the headers
$QUICKTIME\_DIR is an environment variable that would correspond to the ./configure –prefix=$QUICKTIME\_DIR
Created by Eric Wing.
cmake FindHSPELL FindHSPELL
==========
Try to find Hspell
Once done this will define
```
HSPELL_FOUND - system has Hspell
HSPELL_INCLUDE_DIR - the Hspell include directory
HSPELL_LIBRARIES - The libraries needed to use Hspell
HSPELL_DEFINITIONS - Compiler switches required for using Hspell
```
```
HSPELL_VERSION_STRING - The version of Hspell found (x.y)
HSPELL_MAJOR_VERSION - the major version of Hspell
HSPELL_MINOR_VERSION - The minor version of Hspell
```
cmake FindPythonInterp FindPythonInterp
================
Find python interpreter
This module finds if Python interpreter is installed and determines where the executables are. This code sets the following variables:
```
PYTHONINTERP_FOUND - Was the Python executable found
PYTHON_EXECUTABLE - path to the Python interpreter
```
```
PYTHON_VERSION_STRING - Python version found e.g. 2.5.2
PYTHON_VERSION_MAJOR - Python major version found e.g. 2
PYTHON_VERSION_MINOR - Python minor version found e.g. 5
PYTHON_VERSION_PATCH - Python patch version found e.g. 2
```
The Python\_ADDITIONAL\_VERSIONS variable can be used to specify a list of version numbers that should be taken into account when searching for Python. You need to set this variable before calling find\_package(PythonInterp).
If calling both `find_package(PythonInterp)` and `find_package(PythonLibs)`, call `find_package(PythonInterp)` first to get the currently active Python version by default with a consistent version of PYTHON\_LIBRARIES.
cmake CheckFortranSourceCompiles CheckFortranSourceCompiles
==========================
Check if given Fortran source compiles and links into an executable:
```
CHECK_Fortran_SOURCE_COMPILES(<code> <var> [FAIL_REGEX <fail-regex>]
[SRC_EXT <ext>])
```
The arguments are:
`<code>` Source code to try to compile. It must define a PROGRAM entry point.
`<var>` Variable to store whether the source code compiled. Will be created as an internal cache variable.
`FAIL_REGEX <fail-regex>` Fail if test output matches this regex.
`SRC_EXT <ext>` Use source extension `.<ext>` instead of the default `.F`. The following variables may be set before calling this macro to modify the way the check is run:
```
CMAKE_REQUIRED_FLAGS = string of compile command line flags
CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
CMAKE_REQUIRED_INCLUDES = list of include directories
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
CMAKE_REQUIRED_QUIET = execute quietly without messages
```
cmake FindosgFX FindosgFX
=========
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgFX This module defines
OSGFX\_FOUND - Was osgFX found? OSGFX\_INCLUDE\_DIR - Where to find the headers OSGFX\_LIBRARIES - The libraries to link against for the osgFX (use this)
OSGFX\_LIBRARY - The osgFX library OSGFX\_LIBRARY\_DEBUG - The osgFX debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake CTestCoverageCollectGCOV CTestCoverageCollectGCOV
========================
This module provides the `ctest_coverage_collect_gcov` function.
This function runs gcov on all .gcda files found in the binary tree and packages the resulting .gcov files into a tar file. This tarball also contains the following:
* *data.json* defines the source and build directories for use by CDash.
* *Labels.json* indicates any [`LABELS`](../prop_sf/labels#prop_sf:LABELS "LABELS") that have been set on the source files.
* The *uncovered* directory holds any uncovered files found by [`CTEST_EXTRA_COVERAGE_GLOB`](../variable/ctest_extra_coverage_glob#variable:CTEST_EXTRA_COVERAGE_GLOB "CTEST_EXTRA_COVERAGE_GLOB").
After generating this tar file, it can be sent to CDash for display with the [`ctest_submit(CDASH_UPLOAD)`](../command/ctest_submit#command:ctest_submit "ctest_submit") command.
`cdash_coverage_collect_gcov`
```
ctest_coverage_collect_gcov(TARBALL <tarfile>
[SOURCE <source_dir>][BUILD <build_dir>]
[GCOV_COMMAND <gcov_command>]
[GCOV_OPTIONS <options>...]
)
```
Run gcov and package a tar file for CDash. The options are:
`TARBALL <tarfile>` Specify the location of the `.tar` file to be created for later upload to CDash. Relative paths will be interpreted with respect to the top-level build directory.
`SOURCE <source_dir>` Specify the top-level source directory for the build. Default is the value of [`CTEST_SOURCE_DIRECTORY`](../variable/ctest_source_directory#variable:CTEST_SOURCE_DIRECTORY "CTEST_SOURCE_DIRECTORY").
`BUILD <build_dir>` Specify the top-level build directory for the build. Default is the value of [`CTEST_BINARY_DIRECTORY`](../variable/ctest_binary_directory#variable:CTEST_BINARY_DIRECTORY "CTEST_BINARY_DIRECTORY").
`GCOV_COMMAND <gcov_command>` Specify the full path to the `gcov` command on the machine. Default is the value of [`CTEST_COVERAGE_COMMAND`](../variable/ctest_coverage_command#variable:CTEST_COVERAGE_COMMAND "CTEST_COVERAGE_COMMAND").
`GCOV_OPTIONS <options>...` Specify options to be passed to gcov. The `gcov` command is run as `gcov <options>... -o <gcov-dir> <file>.gcda`. If not specified, the default option is just `-b`.
`GLOB` Recursively search for .gcda files in build\_dir rather than determining search locations by reading TargetDirectories.txt.
`DELETE` Delete coverage files after they’ve been packaged into the .tar.
`QUIET` Suppress non-error messages that otherwise would have been printed out by this function.
cmake FindWish FindWish
========
Find wish installation
This module finds if TCL is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:
```
TK_WISH = the path to the wish executable
```
if UNIX is defined, then it will look for the cygwin version first
cmake CPackWIX CPackWIX
========
CPack WiX generator specific options
Variables specific to CPack WiX generator
-----------------------------------------
The following variables are specific to the installers built on Windows using WiX.
`CPACK_WIX_UPGRADE_GUID`
Upgrade GUID (`Product/@UpgradeCode`)
Will be automatically generated unless explicitly provided.
It should be explicitly set to a constant generated globally unique identifier (GUID) to allow your installers to replace existing installations that use the same GUID.
You may for example explicitly set this variable in your CMakeLists.txt to the value that has been generated per default. You should not use GUIDs that you did not generate yourself or which may belong to other projects.
A GUID shall have the following fixed length syntax:
```
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
```
(each X represents an uppercase hexadecimal digit)
`CPACK_WIX_PRODUCT_GUID`
Product GUID (`Product/@Id`)
Will be automatically generated unless explicitly provided.
If explicitly provided this will set the Product Id of your installer.
The installer will abort if it detects a pre-existing installation that uses the same GUID.
The GUID shall use the syntax described for CPACK\_WIX\_UPGRADE\_GUID.
`CPACK_WIX_LICENSE_RTF`
RTF License File
If CPACK\_RESOURCE\_FILE\_LICENSE has an .rtf extension it is used as-is.
If CPACK\_RESOURCE\_FILE\_LICENSE has an .txt extension it is implicitly converted to RTF by the WiX Generator. The expected encoding of the .txt file is UTF-8.
With CPACK\_WIX\_LICENSE\_RTF you can override the license file used by the WiX Generator in case CPACK\_RESOURCE\_FILE\_LICENSE is in an unsupported format or the .txt -> .rtf conversion does not work as expected.
`CPACK_WIX_PRODUCT_ICON`
The Icon shown next to the program name in Add/Remove programs.
If set, this icon is used in place of the default icon.
`CPACK_WIX_UI_REF`
This variable allows you to override the Id of the `<UIRef>` element in the WiX template.
The default is `WixUI_InstallDir` in case no CPack components have been defined and `WixUI_FeatureTree` otherwise.
`CPACK_WIX_UI_BANNER`
The bitmap will appear at the top of all installer pages other than the welcome and completion dialogs.
If set, this image will replace the default banner image.
This image must be 493 by 58 pixels.
`CPACK_WIX_UI_DIALOG`
Background bitmap used on the welcome and completion dialogs.
If this variable is set, the installer will replace the default dialog image.
This image must be 493 by 312 pixels.
`CPACK_WIX_PROGRAM_MENU_FOLDER`
Start menu folder name for launcher.
If this variable is not set, it will be initialized with CPACK\_PACKAGE\_NAME
`CPACK_WIX_CULTURES`
Language(s) of the installer
Languages are compiled into the WixUI extension library. To use them, simply provide the name of the culture. If you specify more than one culture identifier in a comma or semicolon delimited list, the first one that is found will be used. You can find a list of supported languages at: <http://wix.sourceforge.net/manual-wix3/WixUI_localization.htm>
`CPACK_WIX_TEMPLATE`
Template file for WiX generation
If this variable is set, the specified template will be used to generate the WiX wxs file. This should be used if further customization of the output is required.
If this variable is not set, the default MSI template included with CMake will be used.
`CPACK_WIX_PATCH_FILE`
Optional list of XML files with fragments to be inserted into generated WiX sources
This optional variable can be used to specify an XML file that the WiX generator will use to inject fragments into its generated source files.
Patch files understood by the CPack WiX generator roughly follow this RELAX NG compact schema:
```
start = CPackWiXPatch
CPackWiXPatch = element CPackWiXPatch { CPackWiXFragment* }
CPackWiXFragment = element CPackWiXFragment
{
attribute Id { string },
fragmentContent*
}
fragmentContent = element * - CPackWiXFragment
{
(attribute * { text } | text | fragmentContent)*
}
```
Currently fragments can be injected into most Component, File, Directory and Feature elements.
The following additional special Ids can be used:
* `#PRODUCT` for the `<Product>` element.
* `#PRODUCTFEATURE` for the root `<Feature>` element.
The following example illustrates how this works.
Given that the WiX generator creates the following XML element:
```
<Component Id="CM_CP_applications.bin.my_libapp.exe" Guid="*"/>
```
The following XML patch file may be used to inject an Environment element into it:
```
<CPackWiXPatch>
<CPackWiXFragment Id="CM_CP_applications.bin.my_libapp.exe">
<Environment Id="MyEnvironment" Action="set"
Name="MyVariableName" Value="MyVariableValue"/>
</CPackWiXFragment>
</CPackWiXPatch>
```
`CPACK_WIX_EXTRA_SOURCES`
Extra WiX source files
This variable provides an optional list of extra WiX source files (.wxs) that should be compiled and linked. The full path to source files is required.
`CPACK_WIX_EXTRA_OBJECTS`
Extra WiX object files or libraries
This variable provides an optional list of extra WiX object (.wixobj) and/or WiX library (.wixlib) files. The full path to objects and libraries is required.
`CPACK_WIX_EXTENSIONS`
This variable provides a list of additional extensions for the WiX tools light and candle.
`CPACK_WIX_<TOOL>_EXTENSIONS`
This is the tool specific version of CPACK\_WIX\_EXTENSIONS. `<TOOL>` can be either LIGHT or CANDLE.
`CPACK_WIX_<TOOL>_EXTRA_FLAGS`
This list variable allows you to pass additional flags to the WiX tool `<TOOL>`.
Use it at your own risk. Future versions of CPack may generate flags which may be in conflict with your own flags.
`<TOOL>` can be either LIGHT or CANDLE.
`CPACK_WIX_CMAKE_PACKAGE_REGISTRY`
If this variable is set the generated installer will create an entry in the windows registry key `HKEY_LOCAL_MACHINE\Software\Kitware\CMake\Packages\<package>` The value for `<package>` is provided by this variable.
Assuming you also install a CMake configuration file this will allow other CMake projects to find your package with the [`find_package()`](../command/find_package#command:find_package "find_package") command.
`CPACK_WIX_PROPERTY_<PROPERTY>`
This variable can be used to provide a value for the Windows Installer property `<PROPERTY>`
The following list contains some example properties that can be used to customize information under “Programs and Features” (also known as “Add or Remove Programs”)
* ARPCOMMENTS - Comments
* ARPHELPLINK - Help and support information URL
* ARPURLINFOABOUT - General information URL
* ARPURLUPDATEINFO - Update information URL
* ARPHELPTELEPHONE - Help and support telephone number
* ARPSIZE - Size (in kilobytes) of the application
`CPACK_WIX_ROOT_FEATURE_TITLE`
Sets the name of the root install feature in the WIX installer. Same as CPACK\_COMPONENT\_<compName>\_DISPLAY\_NAME for components.
`CPACK_WIX_ROOT_FEATURE_DESCRIPTION`
Sets the description of the root install feature in the WIX installer. Same as CPACK\_COMPONENT\_<compName>\_DESCRIPTION for components.
`CPACK_WIX_SKIP_PROGRAM_FOLDER`
If this variable is set to true, the default install location of the generated package will be CPACK\_PACKAGE\_INSTALL\_DIRECTORY directly. The install location will not be located relatively below ProgramFiles or ProgramFiles64.
Note
Installers created with this feature do not take differences between the system on which the installer is created and the system on which the installer might be used into account.
It is therefor possible that the installer e.g. might try to install onto a drive that is unavailable or unintended or a path that does not follow the localization or convention of the system on which the installation is performed.
`CPACK_WIX_ROOT_FOLDER_ID`
This variable allows specification of a custom root folder ID. The generator specific `<64>` token can be used for folder IDs that come in 32-bit and 64-bit variants. In 32-bit builds the token will expand empty while in 64-bit builds it will expand to `64`.
When unset generated installers will default installing to `ProgramFiles<64>Folder`.
`CPACK_WIX_ROOT`
This variable can optionally be set to the root directory of a custom WiX Toolset installation.
When unspecified CPack will try to locate a WiX Toolset installation via the `WIX` environment variable instead.
| programming_docs |
cmake CPackIFW CPackIFW
========
This module looks for the location of the command line utilities supplied with the Qt Installer Framework ([QtIFW](http://doc.qt.io/qtinstallerframework/index.html)).
The module also defines several commands to control the behavior of the CPack `IFW` generator.
Overview
--------
CPack `IFW` generator helps you to create online and offline binary cross-platform installers with a graphical user interface.
CPack IFW generator prepares project installation and generates configuration and meta information for [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) tools.
The [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) provides a set of tools and utilities to create installers for the supported desktop Qt platforms: Linux, Microsoft Windows, and Mac OS X.
You should also install [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) to use CPack `IFW` generator.
Hints
-----
Generally, the CPack `IFW` generator automatically finds [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) tools, but if you don’t use a default path for installation of the [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) tools, the path may be specified in either a CMake or an environment variable:
`CPACK_IFW_ROOT`
An CMake variable which specifies the location of the [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) tool suite.
The variable will be cached in the `CPackConfig.cmake` file and used at CPack runtime.
`QTIFWDIR`
An environment variable which specifies the location of the [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) tool suite.
Note
The specified path should not contain “bin” at the end (for example: “D:\DevTools\QtIFW2.0.5”).
The [`CPACK_IFW_ROOT`](#variable:CPACK_IFW_ROOT "CPACK_IFW_ROOT") variable has a higher priority and overrides the value of the [`QTIFWDIR`](#variable:QTIFWDIR "QTIFWDIR") variable.
Internationalization
--------------------
Some variables and command arguments support internationalization via CMake script. This is an optional feature.
Installers created by [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) tools have built-in support for internationalization and many phrases are localized to many languages, but this does not apply to the description of the your components and groups that will be distributed.
Localization of the description of your components and groups is useful for users of your installers.
A localized variable or argument can contain a single default value, and a set of pairs the name of the locale and the localized value.
For example:
```
set(LOCALIZABLE_VARIABLE "Default value"
en "English value"
en_US "American value"
en_GB "Great Britain value"
)
```
Variables
---------
You can use the following variables to change behavior of CPack `IFW` generator.
### Debug
`CPACK_IFW_VERBOSE`
Set to `ON` to enable addition debug output. By default is `OFF`.
### Package
`CPACK_IFW_PACKAGE_TITLE`
Name of the installer as displayed on the title bar. By default used [`CPACK_PACKAGE_DESCRIPTION_SUMMARY`](cpack#variable:CPACK_PACKAGE_DESCRIPTION_SUMMARY "CPACK_PACKAGE_DESCRIPTION_SUMMARY").
`CPACK_IFW_PACKAGE_PUBLISHER`
Publisher of the software (as shown in the Windows Control Panel). By default used [`CPACK_PACKAGE_VENDOR`](cpack#variable:CPACK_PACKAGE_VENDOR "CPACK_PACKAGE_VENDOR").
`CPACK_IFW_PRODUCT_URL`
URL to a page that contains product information on your web site.
`CPACK_IFW_PACKAGE_ICON`
Filename for a custom installer icon. The actual file is ‘.icns’ (Mac OS X), ‘.ico’ (Windows). No functionality on Unix.
`CPACK_IFW_PACKAGE_WINDOW_ICON`
Filename for a custom window icon in PNG format for the Installer application.
`CPACK_IFW_PACKAGE_LOGO`
Filename for a logo is used as QWizard::LogoPixmap.
`CPACK_IFW_PACKAGE_WATERMARK`
Filename for a watermark is used as QWizard::WatermarkPixmap.
`CPACK_IFW_PACKAGE_BANNER`
Filename for a banner is used as QWizard::BannerPixmap.
`CPACK_IFW_PACKAGE_BACKGROUND`
Filename for an image used as QWizard::BackgroundPixmap (only used by MacStyle).
`CPACK_IFW_PACKAGE_WIZARD_STYLE`
Wizard style to be used (“Modern”, “Mac”, “Aero” or “Classic”).
`CPACK_IFW_PACKAGE_WIZARD_DEFAULT_WIDTH`
Default width of the wizard in pixels. Setting a banner image will override this.
`CPACK_IFW_PACKAGE_WIZARD_DEFAULT_HEIGHT`
Default height of the wizard in pixels. Setting a watermark image will override this.
`CPACK_IFW_PACKAGE_TITLE_COLOR`
Color of the titles and subtitles (takes an HTML color code, such as “#88FF33”).
`CPACK_IFW_PACKAGE_START_MENU_DIRECTORY`
Name of the default program group for the product in the Windows Start menu.
By default used [`CPACK_IFW_PACKAGE_NAME`](#variable:CPACK_IFW_PACKAGE_NAME "CPACK_IFW_PACKAGE_NAME").
`CPACK_IFW_TARGET_DIRECTORY`
Default target directory for installation. By default used “@ApplicationsDir@/[`CPACK_PACKAGE_INSTALL_DIRECTORY`](cpack#variable:CPACK_PACKAGE_INSTALL_DIRECTORY "CPACK_PACKAGE_INSTALL_DIRECTORY")”
You can use predefined variables.
`CPACK_IFW_ADMIN_TARGET_DIRECTORY`
Default target directory for installation with administrator rights.
You can use predefined variables.
`CPACK_IFW_PACKAGE_GROUP`
The group, which will be used to configure the root package
`CPACK_IFW_PACKAGE_NAME`
The root package name, which will be used if configuration group is not specified
`CPACK_IFW_PACKAGE_MAINTENANCE_TOOL_NAME`
Filename of the generated maintenance tool. The platform-specific executable file extension is appended.
By default used [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) defaults (`maintenancetool`).
`CPACK_IFW_PACKAGE_MAINTENANCE_TOOL_INI_FILE`
Filename for the configuration of the generated maintenance tool.
By default used [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) defaults (`maintenancetool.ini`).
`CPACK_IFW_PACKAGE_ALLOW_NON_ASCII_CHARACTERS`
Set to `ON` if the installation path can contain non-ASCII characters.
Is `ON` for [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) less 2.0 tools.
`CPACK_IFW_PACKAGE_ALLOW_SPACE_IN_PATH`
Set to `OFF` if the installation path cannot contain space characters.
Is `ON` for [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) less 2.0 tools.
`CPACK_IFW_PACKAGE_CONTROL_SCRIPT`
Filename for a custom installer control script.
`CPACK_IFW_PACKAGE_RESOURCES`
List of additional resources (‘.qrc’ files) to include in the installer binary.
You can use [`cpack_ifw_add_package_resources()`](#command:cpack_ifw_add_package_resources "cpack_ifw_add_package_resources") command to resolve relative paths.
`CPACK_IFW_REPOSITORIES_ALL`
The list of remote repositories.
The default value of this variable is computed by CPack and contains all repositories added with command [`cpack_ifw_add_repository()`](#command:cpack_ifw_add_repository "cpack_ifw_add_repository") or updated with command [`cpack_ifw_update_repository()`](#command:cpack_ifw_update_repository "cpack_ifw_update_repository").
`CPACK_IFW_DOWNLOAD_ALL`
If this is `ON` all components will be downloaded. By default is `OFF` or used value from `CPACK_DOWNLOAD_ALL` if set
### Components
`CPACK_IFW_RESOLVE_DUPLICATE_NAMES`
Resolve duplicate names when installing components with groups.
`CPACK_IFW_PACKAGES_DIRECTORIES`
Additional prepared packages dirs that will be used to resolve dependent components.
### Tools
`CPACK_IFW_FRAMEWORK_VERSION`
The version of used [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) tools.
`CPACK_IFW_BINARYCREATOR_EXECUTABLE`
The path to “binarycreator” command line client.
This variable is cached and may be configured if needed.
`CPACK_IFW_REPOGEN_EXECUTABLE`
The path to “repogen” command line client.
This variable is cached and may be configured if needed.
`CPACK_IFW_INSTALLERBASE_EXECUTABLE`
The path to “installerbase” installer executable base.
This variable is cached and may be configured if needed.
`CPACK_IFW_DEVTOOL_EXECUTABLE`
The path to “devtool” command line client.
This variable is cached and may be configured if needed.
Commands
--------
The module defines the following commands:
`cpack_ifw_configure_component`
Sets the arguments specific to the CPack IFW generator.
```
cpack_ifw_configure_component(<compname> [COMMON] [ESSENTIAL] [VIRTUAL]
[FORCED_INSTALLATION] [REQUIRES_ADMIN_RIGHTS]
[NAME <name>]
[DISPLAY_NAME <display_name>] # Note: Internationalization supported
[DESCRIPTION <description>] # Note: Internationalization supported
[UPDATE_TEXT <update_text>]
[VERSION <version>]
[RELEASE_DATE <release_date>]
[SCRIPT <script>]
[PRIORITY|SORTING_PRIORITY <sorting_priority>] # Note: PRIORITY is deprecated
[DEPENDS|DEPENDENCIES <com_id> ...]
[AUTO_DEPEND_ON <comp_id> ...]
[LICENSES <display_name> <file_path> ...]
[DEFAULT <value>]
[USER_INTERFACES <file_path> <file_path> ...]
[TRANSLATIONS <file_path> <file_path> ...])
```
This command should be called after [`cpack_add_component()`](cpackcomponent#command:cpack_add_component "cpack_add_component") command.
`COMMON` if set, then the component will be packaged and installed as part of a group to which it belongs.
`ESSENTIAL` if set, then the package manager stays disabled until that component is updated.
`VIRTUAL` if set, then the component will be hidden from the installer. It is a equivalent of the `HIDDEN` option from the [`cpack_add_component()`](cpackcomponent#command:cpack_add_component "cpack_add_component") command.
`FORCED_INSTALLATION` if set, then the component must always be installed. It is a equivalent of the `REQUARED` option from the [`cpack_add_component()`](cpackcomponent#command:cpack_add_component "cpack_add_component") command.
`REQUIRES_ADMIN_RIGHTS` set it if the component needs to be installed with elevated permissions.
`NAME` is used to create domain-like identification for this component. By default used origin component name.
`DISPLAY_NAME` set to rewrite original name configured by [`cpack_add_component()`](cpackcomponent#command:cpack_add_component "cpack_add_component") command.
`DESCRIPTION` set to rewrite original description configured by [`cpack_add_component()`](cpackcomponent#command:cpack_add_component "cpack_add_component") command.
`UPDATE_TEXT` will be added to the component description if this is an update to the component.
`VERSION` is version of component. By default used [`CPACK_PACKAGE_VERSION`](cpack#variable:CPACK_PACKAGE_VERSION "CPACK_PACKAGE_VERSION").
`RELEASE_DATE` keep empty to auto generate.
`SCRIPT` is a relative or absolute path to operations script for this component.
`PRIORITY | SORTING_PRIORITY` is priority of the component in the tree. The `PRIORITY` option is deprecated and will be removed in a future version of CMake. Please use `SORTING_PRIORITY` option instead.
`DEPENDS | DEPENDENCIES` list of dependency component or component group identifiers in [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) style.
`AUTO_DEPEND_ON` list of identifiers of component or component group in [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) style that this component has an automatic dependency on.
`LICENSES` pair of <display\_name> and <file\_path> of license text for this component. You can specify more then one license.
`DEFAULT` Possible values are: TRUE, FALSE, and SCRIPT. Set to FALSE to disable the component in the installer or to SCRIPT to resolved during runtime (don’t forget add the file of the script as a value of the `SCRIPT` option).
`USER_INTERFACES` is a list of <file\_path> (‘.ui’ files) representing pages to load.
`TRANSLATIONS` is a list of <file\_path> (‘.qm’ files) representing translations to load.
`cpack_ifw_configure_component_group`
Sets the arguments specific to the CPack IFW generator.
```
cpack_ifw_configure_component_group(<groupname> [VIRTUAL]
[FORCED_INSTALLATION] [REQUIRES_ADMIN_RIGHTS]
[NAME <name>]
[DISPLAY_NAME <display_name>] # Note: Internationalization supported
[DESCRIPTION <description>] # Note: Internationalization supported
[UPDATE_TEXT <update_text>]
[VERSION <version>]
[RELEASE_DATE <release_date>]
[SCRIPT <script>]
[PRIORITY|SORTING_PRIORITY <sorting_priority>] # Note: PRIORITY is deprecated
[DEPENDS|DEPENDENCIES <com_id> ...]
[AUTO_DEPEND_ON <comp_id> ...]
[LICENSES <display_name> <file_path> ...]
[DEFAULT <value>]
[USER_INTERFACES <file_path> <file_path> ...]
[TRANSLATIONS <file_path> <file_path> ...])
```
This command should be called after [`cpack_add_component_group()`](cpackcomponent#command:cpack_add_component_group "cpack_add_component_group") command.
`VIRTUAL` if set, then the group will be hidden from the installer. Note that setting this on a root component does not work.
`FORCED_INSTALLATION` if set, then the group must always be installed.
`REQUIRES_ADMIN_RIGHTS` set it if the component group needs to be installed with elevated permissions.
`NAME` is used to create domain-like identification for this component group. By default used origin component group name.
`DISPLAY_NAME` set to rewrite original name configured by [`cpack_add_component_group()`](cpackcomponent#command:cpack_add_component_group "cpack_add_component_group") command.
`DESCRIPTION` set to rewrite original description configured by [`cpack_add_component_group()`](cpackcomponent#command:cpack_add_component_group "cpack_add_component_group") command.
`UPDATE_TEXT` will be added to the component group description if this is an update to the component group.
`VERSION` is version of component group. By default used [`CPACK_PACKAGE_VERSION`](cpack#variable:CPACK_PACKAGE_VERSION "CPACK_PACKAGE_VERSION").
`RELEASE_DATE` keep empty to auto generate.
`SCRIPT` is a relative or absolute path to operations script for this component group.
`PRIORITY | SORTING_PRIORITY` is priority of the component group in the tree. The `PRIORITY` option is deprecated and will be removed in a future version of CMake. Please use `SORTING_PRIORITY` option instead.
`DEPENDS | DEPENDENCIES` list of dependency component or component group identifiers in [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) style.
`AUTO_DEPEND_ON` list of identifiers of component or component group in [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) style that this component group has an automatic dependency on.
`LICENSES` pair of <display\_name> and <file\_path> of license text for this component group. You can specify more then one license.
`DEFAULT` Possible values are: TRUE, FALSE, and SCRIPT. Set to TRUE to preselect the group in the installer (this takes effect only on groups that have no visible child components) or to SCRIPT to resolved during runtime (don’t forget add the file of the script as a value of the `SCRIPT` option).
`USER_INTERFACES` is a list of <file\_path> (‘.ui’ files) representing pages to load.
`TRANSLATIONS` is a list of <file\_path> (‘.qm’ files) representing translations to load.
`cpack_ifw_add_repository`
Add [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) specific remote repository to binary installer.
```
cpack_ifw_add_repository(<reponame> [DISABLED]
URL <url>
[USERNAME <username>]
[PASSWORD <password>]
[DISPLAY_NAME <display_name>])
```
This command will also add the <reponame> repository to a variable [`CPACK_IFW_REPOSITORIES_ALL`](#variable:CPACK_IFW_REPOSITORIES_ALL "CPACK_IFW_REPOSITORIES_ALL").
`DISABLED` if set, then the repository will be disabled by default.
`URL` is points to a list of available components.
`USERNAME` is used as user on a protected repository.
`PASSWORD` is password to use on a protected repository.
`DISPLAY_NAME` is string to display instead of the URL.
`cpack_ifw_update_repository`
Update [QtIFW](http://doc.qt.io/qtinstallerframework/index.html) specific repository from remote repository.
```
cpack_ifw_update_repository(<reponame>
[[ADD|REMOVE] URL <url>]|
[REPLACE OLD_URL <old_url> NEW_URL <new_url>]]
[USERNAME <username>]
[PASSWORD <password>]
[DISPLAY_NAME <display_name>])
```
This command will also add the <reponame> repository to a variable [`CPACK_IFW_REPOSITORIES_ALL`](#variable:CPACK_IFW_REPOSITORIES_ALL "CPACK_IFW_REPOSITORIES_ALL").
`URL` is points to a list of available components.
`OLD_URL` is points to a list that will replaced.
`NEW_URL` is points to a list that will replace to.
`USERNAME` is used as user on a protected repository.
`PASSWORD` is password to use on a protected repository.
`DISPLAY_NAME` is string to display instead of the URL.
`cpack_ifw_add_package_resources`
Add additional resources in the installer binary.
```
cpack_ifw_add_package_resources(<file_path> <file_path> ...)
```
This command will also add the specified files to a variable [`CPACK_IFW_PACKAGE_RESOURCES`](#variable:CPACK_IFW_PACKAGE_RESOURCES "CPACK_IFW_PACKAGE_RESOURCES").
Example usage
-------------
```
set(CPACK_PACKAGE_NAME "MyPackage")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "MyPackage Installation Example")
set(CPACK_PACKAGE_VERSION "1.0.0") # Version of installer
include(CPack)
include(CPackIFW)
cpack_add_component(myapp
DISPLAY_NAME "MyApp"
DESCRIPTION "My Application") # Default description
cpack_ifw_configure_component(myapp
DESCRIPTION ru_RU "Мое Приложение" # Localized description
VERSION "1.2.3" # Version of component
SCRIPT "operations.qs")
cpack_add_component(mybigplugin
DISPLAY_NAME "MyBigPlugin"
DESCRIPTION "My Big Downloadable Plugin"
DOWNLOADED)
cpack_ifw_add_repository(myrepo
URL "http://example.com/ifw/repo/myapp"
DISPLAY_NAME "My Application Repository")
```
Online installer
----------------
By default CPack IFW generator makes offline installer. This means that all components will be packaged into a binary file.
To make a component downloaded, you must set the `DOWNLOADED` option in [`cpack_add_component()`](cpackcomponent#command:cpack_add_component "cpack_add_component").
Then you would use the command [`cpack_configure_downloads()`](cpackcomponent#command:cpack_configure_downloads "cpack_configure_downloads"). If you set `ALL` option all components will be downloaded.
You also can use command [`cpack_ifw_add_repository()`](#command:cpack_ifw_add_repository "cpack_ifw_add_repository") and variable [`CPACK_IFW_DOWNLOAD_ALL`](#variable:CPACK_IFW_DOWNLOAD_ALL "CPACK_IFW_DOWNLOAD_ALL") for more specific configuration.
CPack IFW generator creates “repository” dir in current binary dir. You would copy content of this dir to specified `site` (`url`).
See Also
--------
Qt Installer Framework Manual:
* Index page: <http://doc.qt.io/qtinstallerframework/index.html>
* Component Scripting: <http://doc.qt.io/qtinstallerframework/scripting.html>
* Predefined Variables: <http://doc.qt.io/qtinstallerframework/scripting.html#predefined-variables>
* Promoting Updates: <http://doc.qt.io/qtinstallerframework/ifw-updates.html>
Download Qt Installer Framework for you platform from Qt site: <http://download.qt.io/official_releases/qt-installer-framework>
| programming_docs |
cmake FindImageMagick FindImageMagick
===============
Find the ImageMagick binary suite.
This module will search for a set of ImageMagick tools specified as components in the FIND\_PACKAGE call. Typical components include, but are not limited to (future versions of ImageMagick might have additional components not listed here):
```
animate
compare
composite
conjure
convert
display
identify
import
mogrify
montage
stream
```
If no component is specified in the FIND\_PACKAGE call, then it only searches for the ImageMagick executable directory. This code defines the following variables:
```
ImageMagick_FOUND - TRUE if all components are found.
ImageMagick_EXECUTABLE_DIR - Full path to executables directory.
ImageMagick_<component>_FOUND - TRUE if <component> is found.
ImageMagick_<component>_EXECUTABLE - Full path to <component> executable.
ImageMagick_VERSION_STRING - the version of ImageMagick found
(since CMake 2.8.8)
```
ImageMagick\_VERSION\_STRING will not work for old versions like 5.2.3.
There are also components for the following ImageMagick APIs:
```
Magick++
MagickWand
MagickCore
```
For these components the following variables are set:
```
ImageMagick_FOUND - TRUE if all components are found.
ImageMagick_INCLUDE_DIRS - Full paths to all include dirs.
ImageMagick_LIBRARIES - Full paths to all libraries.
ImageMagick_<component>_FOUND - TRUE if <component> is found.
ImageMagick_<component>_INCLUDE_DIRS - Full path to <component> include dirs.
ImageMagick_<component>_LIBRARIES - Full path to <component> libraries.
```
Example Usages:
```
find_package(ImageMagick)
find_package(ImageMagick COMPONENTS convert)
find_package(ImageMagick COMPONENTS convert mogrify display)
find_package(ImageMagick COMPONENTS Magick++)
find_package(ImageMagick COMPONENTS Magick++ convert)
```
Note that the standard FIND\_PACKAGE features are supported (i.e., QUIET, REQUIRED, etc.).
cmake CMakeExpandImportedTargets CMakeExpandImportedTargets
==========================
Deprecated. Do not use.
This module was once needed to expand imported targets to the underlying libraries they reference on disk for use with the [`try_compile()`](../command/try_compile#command:try_compile "try_compile") and [`try_run()`](../command/try_run#command:try_run "try_run") commands. These commands now support imported libraries in their `LINK_LIBRARIES` options (since CMake 2.8.11 for [`try_compile()`](../command/try_compile#command:try_compile "try_compile") and since CMake 3.2 for [`try_run()`](../command/try_run#command:try_run "try_run")).
This module does not support the policy [`CMP0022`](../policy/cmp0022#policy:CMP0022 "CMP0022") `NEW` behavior or use of the [`INTERFACE_LINK_LIBRARIES`](../prop_tgt/interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES") property because [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") cannot be evaluated during configuration.
```
CMAKE_EXPAND_IMPORTED_TARGETS(<var> LIBRARIES lib1 lib2...libN
[CONFIGURATION <config>])
```
CMAKE\_EXPAND\_IMPORTED\_TARGETS() takes a list of libraries and replaces all imported targets contained in this list with their actual file paths of the referenced libraries on disk, including the libraries from their link interfaces. If a CONFIGURATION is given, it uses the respective configuration of the imported targets if it exists. If no CONFIGURATION is given, it uses the first configuration from ${CMAKE\_CONFIGURATION\_TYPES} if set, otherwise ${CMAKE\_BUILD\_TYPE}.
```
cmake_expand_imported_targets(expandedLibs
LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}
CONFIGURATION "${CMAKE_TRY_COMPILE_CONFIGURATION}" )
```
cmake FindDCMTK FindDCMTK
=========
Find DCMTK libraries and applications
The module defines the following variables:
```
DCMTK_INCLUDE_DIRS - Directories to include to use DCMTK
DCMTK_LIBRARIES - Files to link against to use DCMTK
DCMTK_FOUND - If false, don't try to use DCMTK
DCMTK_DIR - (optional) Source directory for DCMTK
```
Compatibility
-------------
This module is able to find a version of DCMTK that does or does not export a *DCMTKConfig.cmake* file. It applies a two step process:
* Step 1: Attempt to find DCMTK version providing a *DCMTKConfig.cmake* file.
* Step 2: If step 1 failed, rely on *FindDCMTK.cmake* to set `DCMTK_*` variables details below.
[Recent DCMTK](http://git.dcmtk.org/web?p=dcmtk.git;a=commit;h=662ae187c493c6b9a73dd5e3875372cebd0c11fe) provides a *DCMTKConfig.cmake* [`package configuration file`](../manual/cmake-packages.7#manual:cmake-packages(7) "cmake-packages(7)"). To exclusively use the package configuration file (recommended when possible), pass the `NO_MODULE` option to [`find_package()`](../command/find_package#command:find_package "find_package"). For example, `find_package(DCMTK NO_MODULE)`. This requires official DCMTK snapshot *3.6.1\_20140617* or newer.
Until all clients update to the more recent DCMTK, build systems will need to support different versions of DCMTK.
On any given system, the following combinations of DCMTK versions could be considered:
| | | | |
| --- | --- | --- | --- |
| | SYSTEM DCMTK | LOCAL DCMTK | Supported ? |
| Case A | NA | [ ] DCMTKConfig | YES |
| Case B | NA | [X] DCMTKConfig | YES |
| Case C | [ ] DCMTKConfig | NA | YES |
| Case D | [X] DCMTKConfig | NA | YES |
| Case E | [ ] DCMTKConfig | [ ] DCMTKConfig | YES (\*) |
| Case F | [X] DCMTKConfig | [ ] DCMTKConfig | NO |
| Case G | [ ] DCMTKConfig | [X] DCMTKConfig | YES |
| Case H | [X] DCMTKConfig | [X] DCMTKConfig | YES |
(\*) See Troubleshooting section. Legend:
NA ……………: Means that no System or Local DCMTK is available
[ ] DCMTKConfig ..: Means that the version of DCMTK does NOT export a DCMTKConfig.cmake file.
[X] DCMTKConfig ..: Means that the version of DCMTK exports a DCMTKConfig.cmake file.
Troubleshooting
---------------
What to do if my project finds a different version of DCMTK?
Remove DCMTK entry from the CMake cache per [`find_package()`](../command/find_package#command:find_package "find_package") documentation.
cmake FindosgProducer FindosgProducer
===============
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgProducer This module defines
OSGPRODUCER\_FOUND - Was osgProducer found? OSGPRODUCER\_INCLUDE\_DIR - Where to find the headers OSGPRODUCER\_LIBRARIES - The libraries to link for osgProducer (use this)
OSGPRODUCER\_LIBRARY - The osgProducer library OSGPRODUCER\_LIBRARY\_DEBUG - The osgProducer debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake UsePkgConfig UsePkgConfig
============
Obsolete pkg-config module for CMake, use FindPkgConfig instead.
This module defines the following macro:
PKGCONFIG(package includedir libdir linkflags cflags)
Calling PKGCONFIG will fill the desired information into the 4 given arguments, e.g. PKGCONFIG(libart-2.0 LIBART\_INCLUDE\_DIR LIBART\_LINK\_DIR LIBART\_LINK\_FLAGS LIBART\_CFLAGS) if pkg-config was NOT found or the specified software package doesn’t exist, the variable will be empty when the function returns, otherwise they will contain the respective information
cmake CPack CPack
=====
Build binary and source package installers.
Variables common to all CPack generators
----------------------------------------
The CPack module generates binary and source installers in a variety of formats using the cpack program. Inclusion of the CPack module adds two new targets to the resulting makefiles, package and package\_source, which build the binary and source installers, respectively. The generated binary installers contain everything installed via CMake’s INSTALL command (and the deprecated INSTALL\_FILES, INSTALL\_PROGRAMS, and INSTALL\_TARGETS commands).
For certain kinds of binary installers (including the graphical installers on Mac OS X and Windows), CPack generates installers that allow users to select individual application components to install. See CPackComponent module for that.
The CPACK\_GENERATOR variable has different meanings in different contexts. In your CMakeLists.txt file, CPACK\_GENERATOR is a *list of generators*: when run with no other arguments, CPack will iterate over that list and produce one package for each generator. In a CPACK\_PROJECT\_CONFIG\_FILE, though, CPACK\_GENERATOR is a *string naming a single generator*. If you need per-cpack- generator logic to control *other* cpack settings, then you need a CPACK\_PROJECT\_CONFIG\_FILE.
The CMake source tree itself contains a CPACK\_PROJECT\_CONFIG\_FILE. See the top level file CMakeCPackOptions.cmake.in for an example.
If set, the CPACK\_PROJECT\_CONFIG\_FILE is included automatically on a per-generator basis. It only need contain overrides.
Here’s how it works:
* cpack runs
* it includes CPackConfig.cmake
* it iterates over the generators listed in that file’s CPACK\_GENERATOR list variable (unless told to use just a specific one via -G on the command line…)
* foreach generator, it then
+ sets CPACK\_GENERATOR to the one currently being iterated
+ includes the CPACK\_PROJECT\_CONFIG\_FILE
+ produces the package for that generator
This is the key: For each generator listed in CPACK\_GENERATOR in CPackConfig.cmake, cpack will *reset* CPACK\_GENERATOR internally to *the one currently being used* and then include the CPACK\_PROJECT\_CONFIG\_FILE.
Before including this CPack module in your CMakeLists.txt file, there are a variety of variables that can be set to customize the resulting installers. The most commonly-used variables are:
`CPACK_PACKAGE_NAME`
The name of the package (or application). If not specified, defaults to the project name.
`CPACK_PACKAGE_VENDOR`
The name of the package vendor. (e.g., “Kitware”).
`CPACK_PACKAGE_DIRECTORY`
The directory in which CPack is doing its packaging. If it is not set then this will default (internally) to the build dir. This variable may be defined in CPack config file or from the cpack command line option “-B”. If set the command line option override the value found in the config file.
`CPACK_PACKAGE_VERSION_MAJOR`
Package major Version
`CPACK_PACKAGE_VERSION_MINOR`
Package minor Version
`CPACK_PACKAGE_VERSION_PATCH`
Package patch Version
`CPACK_PACKAGE_DESCRIPTION_FILE`
A text file used to describe the project. Used, for example, the introduction screen of a CPack-generated Windows installer to describe the project.
`CPACK_PACKAGE_DESCRIPTION_SUMMARY`
Short description of the project (only a few words). Default value is:
```
${PROJECT_DESCRIPTION}
```
if DESCRIPTION has given to the project() call or CMake generated string with PROJECT\_NAME otherwise.
`CPACK_PACKAGE_FILE_NAME`
The name of the package file to generate, not including the extension. For example, cmake-2.6.1-Linux-i686. The default value is:
```
${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-${CPACK_SYSTEM_NAME}.
```
`CPACK_PACKAGE_INSTALL_DIRECTORY`
Installation directory on the target system. This may be used by some CPack generators like NSIS to create an installation directory e.g., “CMake 2.5” below the installation prefix. All installed element will be put inside this directory.
`CPACK_PACKAGE_ICON`
A branding image that will be displayed inside the installer (used by GUI installers).
`CPACK_PACKAGE_CHECKSUM`
An algorithm that will be used to generate additional file with checksum of the package. Output file name will be:
```
${CPACK_PACKAGE_FILE_NAME}.${CPACK_PACKAGE_CHECKSUM}
```
Supported algorithms are those listed by the [string(<HASH>)](../command/string#supported-hash-algorithms) command.
`CPACK_PROJECT_CONFIG_FILE`
CPack-time project CPack configuration file. This file included at cpack time, once per generator after CPack has set CPACK\_GENERATOR to the actual generator being used. It allows per-generator setting of CPACK\_\* variables at cpack time.
`CPACK_RESOURCE_FILE_LICENSE`
License to be embedded in the installer. It will typically be displayed to the user by the produced installer (often with an explicit “Accept” button, for graphical installers) prior to installation. This license file is NOT added to installed file but is used by some CPack generators like NSIS. If you want to install a license file (may be the same as this one) along with your project you must add an appropriate CMake INSTALL command in your CMakeLists.txt.
`CPACK_RESOURCE_FILE_README`
ReadMe file to be embedded in the installer. It typically describes in some detail the purpose of the project during the installation. Not all CPack generators uses this file.
`CPACK_RESOURCE_FILE_WELCOME`
Welcome file to be embedded in the installer. It welcomes users to this installer. Typically used in the graphical installers on Windows and Mac OS X.
`CPACK_MONOLITHIC_INSTALL`
Disables the component-based installation mechanism. When set the component specification is ignored and all installed items are put in a single “MONOLITHIC” package. Some CPack generators do monolithic packaging by default and may be asked to do component packaging by setting CPACK\_<GENNAME>\_COMPONENT\_INSTALL to 1/TRUE.
`CPACK_GENERATOR`
List of CPack generators to use. If not specified, CPack will create a set of options CPACK\_BINARY\_<GENNAME> (e.g., CPACK\_BINARY\_NSIS) allowing the user to enable/disable individual generators. This variable may be used on the command line as well as in:
```
cpack -D CPACK_GENERATOR="ZIP;TGZ" /path/to/build/tree
```
`CPACK_OUTPUT_CONFIG_FILE`
The name of the CPack binary configuration file. This file is the CPack configuration generated by the CPack module for binary installers. Defaults to CPackConfig.cmake.
`CPACK_PACKAGE_EXECUTABLES`
Lists each of the executables and associated text label to be used to create Start Menu shortcuts. For example, setting this to the list ccmake;CMake will create a shortcut named “CMake” that will execute the installed executable ccmake. Not all CPack generators use it (at least NSIS, WIX and OSXX11 do).
`CPACK_STRIP_FILES`
List of files to be stripped. Starting with CMake 2.6.0 CPACK\_STRIP\_FILES will be a boolean variable which enables stripping of all files (a list of files evaluates to TRUE in CMake, so this change is compatible).
`CPACK_VERBATIM_VARIABLES`
If set to TRUE, values of variables prefixed with [CPACK](#cpack) will be escaped before being written to the configuration files, so that the cpack program receives them exactly as they were specified. If not, characters like quotes and backslashes can cause parsing errors or alter the value received by the cpack program. Defaults to FALSE for backwards compatibility.
* Mandatory : NO
* Default : FALSE
The following CPack variables are specific to source packages, and will not affect binary packages:
`CPACK_SOURCE_PACKAGE_FILE_NAME`
The name of the source package. For example cmake-2.6.1.
`CPACK_SOURCE_STRIP_FILES`
List of files in the source tree that will be stripped. Starting with CMake 2.6.0 CPACK\_SOURCE\_STRIP\_FILES will be a boolean variable which enables stripping of all files (a list of files evaluates to TRUE in CMake, so this change is compatible).
`CPACK_SOURCE_GENERATOR`
List of generators used for the source packages. As with CPACK\_GENERATOR, if this is not specified then CPack will create a set of options (e.g., CPACK\_SOURCE\_ZIP) allowing users to select which packages will be generated.
`CPACK_SOURCE_OUTPUT_CONFIG_FILE`
The name of the CPack source configuration file. This file is the CPack configuration generated by the CPack module for source installers. Defaults to CPackSourceConfig.cmake.
`CPACK_SOURCE_IGNORE_FILES`
Pattern of files in the source tree that won’t be packaged when building a source package. This is a list of regular expression patterns (that must be properly escaped), e.g., /CVS/;/.svn/;.swp$;.#;/#;.\*~;cscope.\*
The following variables are for advanced uses of CPack:
`CPACK_CMAKE_GENERATOR`
What CMake generator should be used if the project is CMake project. Defaults to the value of CMAKE\_GENERATOR few users will want to change this setting.
`CPACK_INSTALL_CMAKE_PROJECTS`
List of four values that specify what project to install. The four values are: Build directory, Project Name, Project Component, Directory. If omitted, CPack will build an installer that installs everything.
`CPACK_SYSTEM_NAME`
System name, defaults to the value of ${CMAKE\_SYSTEM\_NAME}.
`CPACK_PACKAGE_VERSION`
Package full version, used internally. By default, this is built from CPACK\_PACKAGE\_VERSION\_MAJOR, CPACK\_PACKAGE\_VERSION\_MINOR, and CPACK\_PACKAGE\_VERSION\_PATCH.
`CPACK_TOPLEVEL_TAG`
Directory for the installed files.
`CPACK_INSTALL_COMMANDS`
Extra commands to install components.
`CPACK_INSTALLED_DIRECTORIES`
Extra directories to install.
`CPACK_PACKAGE_INSTALL_REGISTRY_KEY`
Registry key used when installing this project. This is only used by installer for Windows. The default value is based on the installation directory.
`CPACK_CREATE_DESKTOP_LINKS`
List of desktop links to create. Each desktop link requires a corresponding start menu shortcut as created by [`CPACK_PACKAGE_EXECUTABLES`](#variable:CPACK_PACKAGE_EXECUTABLES "CPACK_PACKAGE_EXECUTABLES").
`CPACK_BINARY_<GENNAME>`
CPack generated options for binary generators. The CPack.cmake module generates (when CPACK\_GENERATOR is not set) a set of CMake options (see CMake option command) which may then be used to select the CPack generator(s) to be used when launching the package target.
Provide options to choose generators we might check here if the required tools for the generates exist and set the defaults according to the results
cmake GoogleTest GoogleTest
==========
This module defines functions to help use the Google Test infrastructure.
`gtest_add_tests`
Automatically add tests with CTest by scanning source code for Google Test macros:
```
gtest_add_tests(TARGET target
[SOURCES src1...]
[EXTRA_ARGS arg1...]
[WORKING_DIRECTORY dir]
[TEST_PREFIX prefix]
[TEST_SUFFIX suffix]
[SKIP_DEPENDENCY]
[TEST_LIST outVar]
)
```
`TARGET target` This must be a known CMake target. CMake will substitute the location of the built executable when running the test.
`SOURCES src1...` When provided, only the listed files will be scanned for test cases. If this option is not given, the [`SOURCES`](../prop_tgt/sources#prop_tgt:SOURCES "SOURCES") property of the specified `target` will be used to obtain the list of sources.
`EXTRA_ARGS arg1...` Any extra arguments to pass on the command line to each test case.
`WORKING_DIRECTORY dir` Specifies the directory in which to run the discovered test cases. If this option is not provided, the current binary directory is used.
`TEST_PREFIX prefix` Allows the specified `prefix` to be prepended to the name of each discovered test case. This can be useful when the same source files are being used in multiple calls to `gtest_add_test()` but with different `EXTRA_ARGS`.
`TEST_SUFFIX suffix` Similar to `TEST_PREFIX` except the `suffix` is appended to the name of every discovered test case. Both `TEST_PREFIX` and `TEST_SUFFIX` can be specified.
`SKIP_DEPENDENCY` Normally, the function creates a dependency which will cause CMake to be re-run if any of the sources being scanned are changed. This is to ensure that the list of discovered tests is updated. If this behavior is not desired (as may be the case while actually writing the test cases), this option can be used to prevent the dependency from being added.
`TEST_LIST outVar` The variable named by `outVar` will be populated in the calling scope with the list of discovered test cases. This allows the caller to do things like manipulate test properties of the discovered tests.
```
include(GoogleTest)
add_executable(FooTest FooUnitTest.cxx)
gtest_add_tests(TARGET FooTest
TEST_SUFFIX .noArgs
TEST_LIST noArgsTests
)
gtest_add_tests(TARGET FooTest
EXTRA_ARGS --someArg someValue
TEST_SUFFIX .withArgs
TEST_LIST withArgsTests
)
set_tests_properties(${noArgsTests} PROPERTIES TIMEOUT 10)
set_tests_properties(${withArgsTests} PROPERTIES TIMEOUT 20)
```
For backward compatibility reasons, the following form is also supported:
```
gtest_add_tests(exe args files...)
```
`exe` The path to the test executable or the name of a CMake target.
`args` A ;-list of extra arguments to be passed to executable. The entire list must be passed as a single argument. Enclose it in quotes, or pass `""` for no arguments.
`files...` A list of source files to search for tests and test fixtures. Alternatively, use `AUTO` to specify that `exe` is the name of a CMake executable target whose sources should be scanned.
```
include(GoogleTest)
set(FooTestArgs --foo 1 --bar 2)
add_executable(FooTest FooUnitTest.cxx)
gtest_add_tests(FooTest "${FooTestArgs}" AUTO)
```
| programming_docs |
cmake SelectLibraryConfigurations SelectLibraryConfigurations
===========================
select\_library\_configurations( basename )
This macro takes a library base name as an argument, and will choose good values for basename\_LIBRARY, basename\_LIBRARIES, basename\_LIBRARY\_DEBUG, and basename\_LIBRARY\_RELEASE depending on what has been found and set. If only basename\_LIBRARY\_RELEASE is defined, basename\_LIBRARY will be set to the release value, and basename\_LIBRARY\_DEBUG will be set to basename\_LIBRARY\_DEBUG-NOTFOUND. If only basename\_LIBRARY\_DEBUG is defined, then basename\_LIBRARY will take the debug value, and basename\_LIBRARY\_RELEASE will be set to basename\_LIBRARY\_RELEASE-NOTFOUND.
If the generator supports configuration types, then basename\_LIBRARY and basename\_LIBRARIES will be set with debug and optimized flags specifying the library to be used for the given configuration. If no build type has been set or the generator in use does not support configuration types, then basename\_LIBRARY and basename\_LIBRARIES will take only the release value, or the debug value if the release one is not set.
cmake FindGTK2 FindGTK2
========
FindGTK2.cmake
This module can find the GTK2 widget libraries and several of its other optional components like gtkmm, glade, and glademm.
NOTE: If you intend to use version checking, CMake 2.6.2 or later is
```
required.
```
Specify one or more of the following components as you call this find module. See example below.
```
gtk
gtkmm
glade
glademm
```
The following variables will be defined for your use
```
GTK2_FOUND - Were all of your specified components found?
GTK2_INCLUDE_DIRS - All include directories
GTK2_LIBRARIES - All libraries
GTK2_TARGETS - All imported targets
GTK2_DEFINITIONS - Additional compiler flags
```
```
GTK2_VERSION - The version of GTK2 found (x.y.z)
GTK2_MAJOR_VERSION - The major version of GTK2
GTK2_MINOR_VERSION - The minor version of GTK2
GTK2_PATCH_VERSION - The patch version of GTK2
```
Optional variables you can define prior to calling this module:
```
GTK2_DEBUG - Enables verbose debugging of the module
GTK2_ADDITIONAL_SUFFIXES - Allows defining additional directories to
search for include files
```
================= Example Usage:
```
Call find_package() once, here are some examples to pick from:
```
```
Require GTK 2.6 or later
find_package(GTK2 2.6 REQUIRED gtk)
```
```
Require GTK 2.10 or later and Glade
find_package(GTK2 2.10 REQUIRED gtk glade)
```
```
Search for GTK/GTKMM 2.8 or later
find_package(GTK2 2.8 COMPONENTS gtk gtkmm)
```
```
if(GTK2_FOUND)
include_directories(${GTK2_INCLUDE_DIRS})
add_executable(mygui mygui.cc)
target_link_libraries(mygui ${GTK2_LIBRARIES})
endif()
```
cmake FindVTK FindVTK
=======
This module no longer exists.
This module existed in versions of CMake prior to 3.1, but became only a thin wrapper around `find_package(VTK NO_MODULE)` to provide compatibility for projects using long-outdated conventions. Now `find_package(VTK)` will search for `VTKConfig.cmake` directly.
cmake FindUnixCommands FindUnixCommands
================
Find Unix commands, including the ones from Cygwin
This module looks for the Unix commands bash, cp, gzip, mv, rm, and tar and stores the result in the variables BASH, CP, GZIP, MV, RM, and TAR.
cmake FindPostgreSQL FindPostgreSQL
==============
Find the PostgreSQL installation.
This module defines
```
PostgreSQL_LIBRARIES - the PostgreSQL libraries needed for linking
PostgreSQL_INCLUDE_DIRS - the directories of the PostgreSQL headers
PostgreSQL_LIBRARY_DIRS - the link directories for PostgreSQL libraries
PostgreSQL_VERSION_STRING - the version of PostgreSQL found (since CMake 2.8.8)
```
cmake CMakeParseArguments CMakeParseArguments
===================
This module once implemented the [`cmake_parse_arguments()`](../command/cmake_parse_arguments#command:cmake_parse_arguments "cmake_parse_arguments") command that is now implemented natively by CMake. It is now an empty placeholder for compatibility with projects that include it to get the command from CMake 3.4 and lower.
cmake FindBZip2 FindBZip2
=========
Try to find BZip2
IMPORTED Targets
----------------
This module defines [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target `BZip2::BZip2`, if BZip2 has been found.
Result Variables
----------------
This module defines the following variables:
```
BZIP2_FOUND - system has BZip2
BZIP2_INCLUDE_DIR - the BZip2 include directory
BZIP2_LIBRARIES - Link these to use BZip2
BZIP2_NEED_PREFIX - this is set if the functions are prefixed with BZ2_
BZIP2_VERSION_STRING - the version of BZip2 found (since CMake 2.8.8)
```
cmake UseEcos UseEcos
=======
This module defines variables and macros required to build eCos application.
This file contains the following macros: ECOS\_ADD\_INCLUDE\_DIRECTORIES() - add the eCos include dirs ECOS\_ADD\_EXECUTABLE(name source1 … sourceN ) - create an eCos executable ECOS\_ADJUST\_DIRECTORY(VAR source1 … sourceN ) - adjusts the path of the source files and puts the result into VAR
Macros for selecting the toolchain: ECOS\_USE\_ARM\_ELF\_TOOLS() - enable the ARM ELF toolchain for the directory where it is called ECOS\_USE\_I386\_ELF\_TOOLS() - enable the i386 ELF toolchain for the directory where it is called ECOS\_USE\_PPC\_EABI\_TOOLS() - enable the PowerPC toolchain for the directory where it is called
It contains the following variables: ECOS\_DEFINITIONS ECOSCONFIG\_EXECUTABLE ECOS\_CONFIG\_FILE - defaults to ecos.ecc, if your eCos configuration file has a different name, adjust this variable for internal use only:
```
ECOS_ADD_TARGET_LIB
```
cmake TestBigEndian TestBigEndian
=============
Define macro to determine endian type
Check if the system is big endian or little endian
```
TEST_BIG_ENDIAN(VARIABLE)
VARIABLE - variable to store the result to
```
cmake CheckFortranFunctionExists CheckFortranFunctionExists
==========================
macro which checks if the Fortran function exists
CHECK\_FORTRAN\_FUNCTION\_EXISTS(FUNCTION VARIABLE)
```
FUNCTION - the name of the Fortran function
VARIABLE - variable to store the result
Will be created as an internal cache variable.
```
The following variables may be set before calling this macro to modify the way the check is run:
```
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
```
cmake FindGDAL FindGDAL
========
Locate gdal
This module accepts the following environment variables:
```
GDAL_DIR or GDAL_ROOT - Specify the location of GDAL
```
This module defines the following CMake variables:
```
GDAL_FOUND - True if libgdal is found
GDAL_LIBRARY - A variable pointing to the GDAL library
GDAL_INCLUDE_DIR - Where to find the headers
```
cmake FindOpenSceneGraph FindOpenSceneGraph
==================
Find OpenSceneGraph
This module searches for the OpenSceneGraph core “osg” library as well as OpenThreads, and whatever additional COMPONENTS (nodekits) that you specify.
```
See http://www.openscenegraph.org
```
NOTE: To use this module effectively you must either require CMake >= 2.6.3 with cmake\_minimum\_required(VERSION 2.6.3) or download and place FindOpenThreads.cmake, Findosg\_functions.cmake, Findosg.cmake, and Find<etc>.cmake files into your CMAKE\_MODULE\_PATH.
This module accepts the following variables (note mixed case)
```
OpenSceneGraph_DEBUG - Enable debugging output
```
```
OpenSceneGraph_MARK_AS_ADVANCED - Mark cache variables as advanced
automatically
```
The following environment variables are also respected for finding the OSG and it’s various components. CMAKE\_PREFIX\_PATH can also be used for this (see find\_library() CMake documentation).
`<MODULE>_DIR` (where MODULE is of the form “OSGVOLUME” and there is a FindosgVolume.cmake file)
`OSG_DIR`
`OSGDIR`
`OSG_ROOT` [CMake 2.8.10]: The CMake variable OSG\_DIR can now be used as well to influence detection, instead of needing to specify an environment variable.
This module defines the following output variables:
```
OPENSCENEGRAPH_FOUND - Was the OSG and all of the specified components found?
```
```
OPENSCENEGRAPH_VERSION - The version of the OSG which was found
```
```
OPENSCENEGRAPH_INCLUDE_DIRS - Where to find the headers
```
```
OPENSCENEGRAPH_LIBRARIES - The OSG libraries
```
================================== Example Usage:
```
find_package(OpenSceneGraph 2.0.0 REQUIRED osgDB osgUtil)
# libOpenThreads & libosg automatically searched
include_directories(${OPENSCENEGRAPH_INCLUDE_DIRS})
```
```
add_executable(foo foo.cc)
target_link_libraries(foo ${OPENSCENEGRAPH_LIBRARIES})
```
cmake CheckIncludeFileCXX CheckIncludeFileCXX
===================
Provides a macro to check if a header file can be included in `CXX`.
`CHECK_INCLUDE_FILE_CXX`
```
CHECK_INCLUDE_FILE_CXX(<include> <variable> [<flags>])
```
Check if the given `<include>` file may be included in a `CXX` source file and store the result in an internal cache entry named `<variable>`. The optional third argument may be used to add compilation flags to the check (or use `CMAKE_REQUIRED_FLAGS` below).
The following variables may be set before calling this macro to modify the way the check is run:
`CMAKE_REQUIRED_FLAGS` string of compile command line flags
`CMAKE_REQUIRED_DEFINITIONS` list of macros to define (-DFOO=bar)
`CMAKE_REQUIRED_INCLUDES` list of include directories
`CMAKE_REQUIRED_QUIET` execute quietly without messages See modules [`CheckIncludeFile`](checkincludefile#module:CheckIncludeFile "CheckIncludeFile") and [`CheckIncludeFiles`](checkincludefiles#module:CheckIncludeFiles "CheckIncludeFiles") to check for one or more `C` headers.
cmake FindPNG FindPNG
=======
Find libpng, the official reference library for the PNG image format.
Imported targets
----------------
This module defines the following [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target:
`PNG::PNG` The libpng library, if found. Result variables
----------------
This module will set the following variables in your project:
`PNG_INCLUDE_DIRS` where to find png.h, etc.
`PNG_LIBRARIES` the libraries to link against to use PNG.
`PNG_DEFINITIONS` You should add\_definitions(${PNG\_DEFINITIONS}) before compiling code that includes png library files.
`PNG_FOUND` If false, do not try to use PNG.
`PNG_VERSION_STRING` the version of the PNG library found (since CMake 2.8.8) Obsolete variables
------------------
The following variables may also be set, for backwards compatibility:
`PNG_LIBRARY` where to find the PNG library.
`PNG_INCLUDE_DIR` where to find the PNG headers (same as PNG\_INCLUDE\_DIRS) Since PNG depends on the ZLib compression library, none of the above will be defined unless ZLib can be found.
cmake UsewxWidgets UsewxWidgets
============
Convenience include for using wxWidgets library.
Determines if wxWidgets was FOUND and sets the appropriate libs, incdirs, flags, etc. INCLUDE\_DIRECTORIES and LINK\_DIRECTORIES are called.
USAGE
```
# Note that for MinGW users the order of libs is important!
find_package(wxWidgets REQUIRED net gl core base)
include(${wxWidgets_USE_FILE})
# and for each of your dependent executable/library targets:
target_link_libraries(<YourTarget> ${wxWidgets_LIBRARIES})
```
DEPRECATED
```
LINK_LIBRARIES is not called in favor of adding dependencies per target.
```
AUTHOR
```
Jan Woetzel <jw -at- mip.informatik.uni-kiel.de>
```
cmake FindGCCXML FindGCCXML
==========
Find the GCC-XML front-end executable.
This module will define the following variables:
```
GCCXML - the GCC-XML front-end executable.
```
cmake FindHDF5 FindHDF5
========
Find HDF5, a library for reading and writing self describing array data.
This module invokes the HDF5 wrapper compiler that should be installed alongside HDF5. Depending upon the HDF5 Configuration, the wrapper compiler is called either h5cc or h5pcc. If this succeeds, the module will then call the compiler with the -show argument to see what flags are used when compiling an HDF5 client application.
The module will optionally accept the COMPONENTS argument. If no COMPONENTS are specified, then the find module will default to finding only the HDF5 C library. If one or more COMPONENTS are specified, the module will attempt to find the language bindings for the specified components. The only valid components are C, CXX, Fortran, HL, and Fortran\_HL. If the COMPONENTS argument is not given, the module will attempt to find only the C bindings.
On UNIX systems, this module will read the variable HDF5\_USE\_STATIC\_LIBRARIES to determine whether or not to prefer a static link to a dynamic link for HDF5 and all of it’s dependencies. To use this feature, make sure that the HDF5\_USE\_STATIC\_LIBRARIES variable is set before the call to find\_package.
To provide the module with a hint about where to find your HDF5 installation, you can set the environment variable HDF5\_ROOT. The Find module will then look in this path when searching for HDF5 executables, paths, and libraries.
Both the serial and parallel HDF5 wrappers are considered and the first directory to contain either one will be used. In the event that both appear in the same directory the serial version is preferentially selected. This behavior can be reversed by setting the variable HDF5\_PREFER\_PARALLEL to true.
In addition to finding the includes and libraries required to compile an HDF5 client application, this module also makes an effort to find tools that come with the HDF5 distribution that may be useful for regression testing.
This module will define the following variables:
```
HDF5_FOUND - true if HDF5 was found on the system
HDF5_VERSION - HDF5 version in format Major.Minor.Release
HDF5_INCLUDE_DIRS - Location of the hdf5 includes
HDF5_INCLUDE_DIR - Location of the hdf5 includes (deprecated)
HDF5_DEFINITIONS - Required compiler definitions for HDF5
HDF5_LIBRARIES - Required libraries for all requested bindings
HDF5_HL_LIBRARIES - Required libraries for the HDF5 high level API for all
bindings, if the HL component is enabled
```
Available components are: C CXX Fortran and HL. For each enabled language binding, a corresponding HDF5\_${LANG}\_LIBRARIES variable, and potentially HDF5\_${LANG}\_DEFINITIONS, will be defined. If the HL component is enabled, then an HDF5\_${LANG}\_HL\_LIBRARIES will also be defined. With all components enabled, the following variables will be defined:
```
HDF5_C_DEFINITIONS -- Required compiler definitions for HDF5 C bindings
HDF5_CXX_DEFINITIONS -- Required compiler definitions for HDF5 C++ bindings
HDF5_Fortran_DEFINITIONS -- Required compiler definitions for HDF5 Fortran bindings
HDF5_C_INCLUDE_DIRS -- Required include directories for HDF5 C bindings
HDF5_CXX_INCLUDE_DIRS -- Required include directories for HDF5 C++ bindings
HDF5_Fortran_INCLUDE_DIRS -- Required include directories for HDF5 Fortran bindings
HDF5_C_LIBRARIES - Required libraries for the HDF5 C bindings
HDF5_CXX_LIBRARIES - Required libraries for the HDF5 C++ bindings
HDF5_Fortran_LIBRARIES - Required libraries for the HDF5 Fortran bindings
HDF5_C_HL_LIBRARIES - Required libraries for the high level C bindings
HDF5_CXX_HL_LIBRARIES - Required libraries for the high level C++ bindings
HDF5_Fortran_HL_LIBRARIES - Required libraries for the high level Fortran
bindings.
HDF5_IS_PARALLEL - Whether or not HDF5 was found with parallel IO support
HDF5_C_COMPILER_EXECUTABLE - the path to the HDF5 C wrapper compiler
HDF5_CXX_COMPILER_EXECUTABLE - the path to the HDF5 C++ wrapper compiler
HDF5_Fortran_COMPILER_EXECUTABLE - the path to the HDF5 Fortran wrapper compiler
HDF5_C_COMPILER_EXECUTABLE_NO_INTERROGATE - path to the primary C compiler
which is also the HDF5 wrapper
HDF5_CXX_COMPILER_EXECUTABLE_NO_INTERROGATE - path to the primary C++
compiler which is also
the HDF5 wrapper
HDF5_Fortran_COMPILER_EXECUTABLE_NO_INTERROGATE - path to the primary
Fortran compiler which
is also the HDF5 wrapper
HDF5_DIFF_EXECUTABLE - the path to the HDF5 dataset comparison tool
```
The following variable can be set to guide the search for HDF5 libraries and includes:
`HDF5_ROOT` Specify the path to the HDF5 installation to use.
`HDF5_FIND_DEBUG` Set to a true value to get some extra debugging output.
`HDF5_NO_FIND_PACKAGE_CONFIG_FILE` Set to a true value to skip trying to find `hdf5-config.cmake`.
cmake AndroidTestUtilities AndroidTestUtilities
====================
Create a test that automatically loads specified data onto an Android device.
Introduction
------------
Use this module to push data needed for testing an Android device behavior onto a connected Android device. The module will accept files and libraries as well as separate destinations for each. It will create a test that loads the files into a device object store and link to them from the specified destination. The files are only uploaded if they are not already in the object store.
For example:
```
include(AndroidTestUtilities)
android_add_test_data(
example_setup_test
FILES <files>...
LIBS <libs>...
DEVICE_TEST_DIR "/data/local/tests/example"
DEVICE_OBJECT_STORE "/sdcard/.ExternalData/SHA"
)
```
At build time a test named “example\_setup\_test” will be created. Run this test on the command line with [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") to load the data onto the Android device.
Module Functions
----------------
`android_add_test_data`
```
android_add_test_data(<test-name>
[FILES <files>...] [FILES_DEST <device-dir>]
[LIBS <libs>...] [LIBS_DEST <device-dir>]
[DEVICE_OBJECT_STORE <device-dir>]
[DEVICE_TEST_DIR <device-dir>]
[NO_LINK_REGEX <strings>...]
)
```
The `android_add_test_data` function is used to copy files and libraries needed to run project-specific tests. On the host operating system, this is done at build time. For on-device testing, the files are loaded onto the device by the manufactured test at run time.
This function accepts the following named parameters:
`FILES <files>...` zero or more files needed for testing
`LIBS <libs>...` zero or more libraries needed for testing
`FILES_DEST <device-dir>` absolute path where the data files are expected to be
`LIBS_DEST <device-dir>` absolute path where the libraries are expected to be
`DEVICE_OBJECT_STORE <device-dir>` absolute path to the location where the data is stored on-device
`DEVICE_TEST_DIR <device-dir>` absolute path to the root directory of the on-device test location
`NO_LINK_REGEX <strings>...` list of regex strings matching the names of files that should be copied from the object store to the testing directory
cmake FindosgSim FindosgSim
==========
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgSim This module defines
OSGSIM\_FOUND - Was osgSim found? OSGSIM\_INCLUDE\_DIR - Where to find the headers OSGSIM\_LIBRARIES - The libraries to link for osgSim (use this)
OSGSIM\_LIBRARY - The osgSim library OSGSIM\_LIBRARY\_DEBUG - The osgSim debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
| programming_docs |
cmake FindTIFF FindTIFF
========
Find the TIFF library (libtiff).
Imported targets
----------------
This module defines the following [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets:
`TIFF::TIFF` The TIFF library, if found. Result variables
----------------
This module will set the following variables in your project:
`TIFF_FOUND` true if the TIFF headers and libraries were found
`TIFF_INCLUDE_DIR` the directory containing the TIFF headers
`TIFF_INCLUDE_DIRS` the directory containing the TIFF headers
`TIFF_LIBRARIES` TIFF libraries to be linked Cache variables
---------------
The following cache variables may also be set:
`TIFF_INCLUDE_DIR` the directory containing the TIFF headers
`TIFF_LIBRARY` the path to the TIFF library
cmake FindArmadillo FindArmadillo
=============
Find Armadillo
Find the Armadillo C++ library
Using Armadillo:
```
find_package(Armadillo REQUIRED)
include_directories(${ARMADILLO_INCLUDE_DIRS})
add_executable(foo foo.cc)
target_link_libraries(foo ${ARMADILLO_LIBRARIES})
```
This module sets the following variables:
```
ARMADILLO_FOUND - set to true if the library is found
ARMADILLO_INCLUDE_DIRS - list of required include directories
ARMADILLO_LIBRARIES - list of libraries to be linked
ARMADILLO_VERSION_MAJOR - major version number
ARMADILLO_VERSION_MINOR - minor version number
ARMADILLO_VERSION_PATCH - patch version number
ARMADILLO_VERSION_STRING - version number as a string (ex: "1.0.4")
ARMADILLO_VERSION_NAME - name of the version (ex: "Antipodean Antileech")
```
cmake CMakeBackwardCompatibilityCXX CMakeBackwardCompatibilityCXX
=============================
define a bunch of backwards compatibility variables
```
CMAKE_ANSI_CXXFLAGS - flag for ansi c++
CMAKE_HAS_ANSI_STRING_STREAM - has <strstream>
include(TestForANSIStreamHeaders)
include(CheckIncludeFileCXX)
include(TestForSTDNamespace)
include(TestForANSIForScope)
```
cmake FindSDL FindSDL
=======
Locate SDL library
This module defines
```
SDL_LIBRARY, the name of the library to link against
SDL_FOUND, if false, do not try to link to SDL
SDL_INCLUDE_DIR, where to find SDL.h
SDL_VERSION_STRING, human-readable string containing the version of SDL
```
This module responds to the flag:
```
SDL_BUILDING_LIBRARY
If this is defined, then no SDL_main will be linked in because
only applications need main().
Otherwise, it is assumed you are building an application and this
module will attempt to locate and set the proper link flags
as part of the returned SDL_LIBRARY variable.
```
Don’t forget to include SDLmain.h and SDLmain.m your project for the OS X framework based version. (Other versions link to -lSDLmain which this module will try to find on your behalf.) Also for OS X, this module will automatically add the -framework Cocoa on your behalf.
Additional Note: If you see an empty SDL\_LIBRARY\_TEMP in your configuration and no SDL\_LIBRARY, it means CMake did not find your SDL library (SDL.dll, libsdl.so, SDL.framework, etc). Set SDL\_LIBRARY\_TEMP to point to your SDL library, and configure again. Similarly, if you see an empty SDLMAIN\_LIBRARY, you should set this value as appropriate. These values are used to generate the final SDL\_LIBRARY variable, but when these values are unset, SDL\_LIBRARY does not get created.
$SDLDIR is an environment variable that would correspond to the ./configure –prefix=$SDLDIR used in building SDL. l.e.galup 9-20-02
Modified by Eric Wing. Added code to assist with automated building by using environmental variables and providing a more controlled/consistent search behavior. Added new modifications to recognize OS X frameworks and additional Unix paths (FreeBSD, etc). Also corrected the header search path to follow “proper” SDL guidelines. Added a search for SDLmain which is needed by some platforms. Added a search for threads which is needed by some platforms. Added needed compile switches for MinGW.
On OSX, this will prefer the Framework version (if found) over others. People will have to manually change the cache values of SDL\_LIBRARY to override this selection or set the CMake environment CMAKE\_INCLUDE\_PATH to modify the search paths.
Note that the header path has changed from SDL/SDL.h to just SDL.h This needed to change because “proper” SDL convention is #include “SDL.h”, not <SDL/SDL.h>. This is done for portability reasons because not all systems place things in SDL/ (see FreeBSD).
cmake FindMPEG FindMPEG
========
Find the native MPEG includes and library
This module defines
```
MPEG_INCLUDE_DIR, where to find MPEG.h, etc.
MPEG_LIBRARIES, the libraries required to use MPEG.
MPEG_FOUND, If false, do not try to use MPEG.
```
also defined, but not for general use are
```
MPEG_mpeg2_LIBRARY, where to find the MPEG library.
MPEG_vo_LIBRARY, where to find the vo library.
```
cmake FindLua FindLua
=======
Locate Lua library This module defines
```
LUA_FOUND - if false, do not try to link to Lua
LUA_LIBRARIES - both lua and lualib
LUA_INCLUDE_DIR - where to find lua.h
LUA_VERSION_STRING - the version of Lua found
LUA_VERSION_MAJOR - the major version of Lua
LUA_VERSION_MINOR - the minor version of Lua
LUA_VERSION_PATCH - the patch version of Lua
```
Note that the expected include convention is
```
#include "lua.h"
```
and not
```
#include <lua/lua.h>
```
This is because, the lua location is not standardized and may exist in locations other than lua/
cmake FindosgManipulator FindosgManipulator
==================
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgManipulator This module defines
OSGMANIPULATOR\_FOUND - Was osgManipulator found? OSGMANIPULATOR\_INCLUDE\_DIR - Where to find the headers OSGMANIPULATOR\_LIBRARIES - The libraries to link for osgManipulator (use this)
OSGMANIPULATOR\_LIBRARY - The osgManipulator library OSGMANIPULATOR\_LIBRARY\_DEBUG - The osgManipulator debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake FindPkgConfig FindPkgConfig
=============
A `pkg-config` module for CMake.
Finds the `pkg-config` executable and add the [`pkg_check_modules()`](#command:pkg_check_modules "pkg_check_modules") and [`pkg_search_module()`](#command:pkg_search_module "pkg_search_module") commands.
In order to find the `pkg-config` executable, it uses the [`PKG_CONFIG_EXECUTABLE`](#variable:PKG_CONFIG_EXECUTABLE "PKG_CONFIG_EXECUTABLE") variable or the `PKG_CONFIG` environment variable first.
`pkg_get_variable`
Retrieves the value of a variable from a package:
```
pkg_get_variable(<RESULT> <MODULE> <VARIABLE>)
```
If multiple values are returned variable will contain a [;-list](../manual/cmake-language.7#cmake-language-lists).
For example:
```
pkg_get_variable(GI_GIRDIR gobject-introspection-1.0 girdir)
```
`pkg_check_modules`
Checks for all the given modules.
```
pkg_check_modules(<PREFIX> [REQUIRED] [QUIET]
[NO_CMAKE_PATH] [NO_CMAKE_ENVIRONMENT_PATH]
[IMPORTED_TARGET]
<MODULE> [<MODULE>]*)
```
When the `REQUIRED` argument was set, macros will fail with an error when module(s) could not be found.
When the `QUIET` argument is set, no status messages will be printed.
By default, if [`CMAKE_MINIMUM_REQUIRED_VERSION`](../variable/cmake_minimum_required_version#variable:CMAKE_MINIMUM_REQUIRED_VERSION "CMAKE_MINIMUM_REQUIRED_VERSION") is 3.1 or later, or if [`PKG_CONFIG_USE_CMAKE_PREFIX_PATH`](#variable:PKG_CONFIG_USE_CMAKE_PREFIX_PATH "PKG_CONFIG_USE_CMAKE_PREFIX_PATH") is set, the [`CMAKE_PREFIX_PATH`](../variable/cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH"), [`CMAKE_FRAMEWORK_PATH`](../variable/cmake_framework_path#variable:CMAKE_FRAMEWORK_PATH "CMAKE_FRAMEWORK_PATH"), and [`CMAKE_APPBUNDLE_PATH`](../variable/cmake_appbundle_path#variable:CMAKE_APPBUNDLE_PATH "CMAKE_APPBUNDLE_PATH") cache and environment variables will be added to `pkg-config` search path. The `NO_CMAKE_PATH` and `NO_CMAKE_ENVIRONMENT_PATH` arguments disable this behavior for the cache variables and the environment variables, respectively. The `IMPORTED_TARGET` argument will create an imported target named PkgConfig::<PREFIX>> that can be passed directly as an argument to [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries").
It sets the following variables:
```
PKG_CONFIG_FOUND ... if pkg-config executable was found
PKG_CONFIG_EXECUTABLE ... pathname of the pkg-config program
PKG_CONFIG_VERSION_STRING ... the version of the pkg-config program found
(since CMake 2.8.8)
```
For the following variables two sets of values exist; first one is the common one and has the given PREFIX. The second set contains flags which are given out when `pkg-config` was called with the `--static` option.
```
<XPREFIX>_FOUND ... set to 1 if module(s) exist
<XPREFIX>_LIBRARIES ... only the libraries (w/o the '-l')
<XPREFIX>_LIBRARY_DIRS ... the paths of the libraries (w/o the '-L')
<XPREFIX>_LDFLAGS ... all required linker flags
<XPREFIX>_LDFLAGS_OTHER ... all other linker flags
<XPREFIX>_INCLUDE_DIRS ... the '-I' preprocessor flags (w/o the '-I')
<XPREFIX>_CFLAGS ... all required cflags
<XPREFIX>_CFLAGS_OTHER ... the other compiler flags
```
```
<XPREFIX> = <PREFIX> for common case
<XPREFIX> = <PREFIX>_STATIC for static linking
```
Every variable containing multiple values will be a [;-list](../manual/cmake-language.7#cmake-language-lists).
There are some special variables whose prefix depends on the count of given modules. When there is only one module, <PREFIX> stays unchanged. When there are multiple modules, the prefix will be changed to <PREFIX>\_<MODNAME>:
```
<XPREFIX>_VERSION ... version of the module
<XPREFIX>_PREFIX ... prefix-directory of the module
<XPREFIX>_INCLUDEDIR ... include-dir of the module
<XPREFIX>_LIBDIR ... lib-dir of the module
```
```
<XPREFIX> = <PREFIX> when |MODULES| == 1, else
<XPREFIX> = <PREFIX>_<MODNAME>
```
A <MODULE> parameter can have the following formats:
```
{MODNAME} ... matches any version
{MODNAME}>={VERSION} ... at least version <VERSION> is required
{MODNAME}={VERSION} ... exactly version <VERSION> is required
{MODNAME}<={VERSION} ... modules must not be newer than <VERSION>
```
Examples
```
pkg_check_modules (GLIB2 glib-2.0)
```
```
pkg_check_modules (GLIB2 glib-2.0>=2.10)
```
Requires at least version 2.10 of glib2 and defines e.g. `GLIB2_VERSION=2.10.3`
```
pkg_check_modules (FOO glib-2.0>=2.10 gtk+-2.0)
```
Requires both glib2 and gtk2, and defines e.g. `FOO_glib-2.0_VERSION=2.10.3` and `FOO_gtk+-2.0_VERSION=2.8.20`
```
pkg_check_modules (XRENDER REQUIRED xrender)
```
Defines for example:
```
XRENDER_LIBRARIES=Xrender;X11``
XRENDER_STATIC_LIBRARIES=Xrender;X11;pthread;Xau;Xdmcp
```
`pkg_search_module`
Same as [`pkg_check_modules()`](#command:pkg_check_modules "pkg_check_modules"), but instead it checks for given modules and uses the first working one.
```
pkg_search_module(<PREFIX> [REQUIRED] [QUIET]
[NO_CMAKE_PATH] [NO_CMAKE_ENVIRONMENT_PATH]
[IMPORTED_TARGET]
<MODULE> [<MODULE>]*)
```
Examples
```
pkg_search_module (BAR libxml-2.0 libxml2 libxml>=2)
```
`PKG_CONFIG_EXECUTABLE`
Path to the pkg-config executable.
`PKG_CONFIG_USE_CMAKE_PREFIX_PATH`
Whether [`pkg_check_modules()`](#command:pkg_check_modules "pkg_check_modules") and [`pkg_search_module()`](#command:pkg_search_module "pkg_search_module") should add the paths in [`CMAKE_PREFIX_PATH`](../variable/cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH"), [`CMAKE_FRAMEWORK_PATH`](../variable/cmake_framework_path#variable:CMAKE_FRAMEWORK_PATH "CMAKE_FRAMEWORK_PATH"), and [`CMAKE_APPBUNDLE_PATH`](../variable/cmake_appbundle_path#variable:CMAKE_APPBUNDLE_PATH "CMAKE_APPBUNDLE_PATH") cache and environment variables to `pkg-config` search path.
If this variable is not set, this behavior is enabled by default if [`CMAKE_MINIMUM_REQUIRED_VERSION`](../variable/cmake_minimum_required_version#variable:CMAKE_MINIMUM_REQUIRED_VERSION "CMAKE_MINIMUM_REQUIRED_VERSION") is 3.1 or later, disabled otherwise.
cmake CheckTypeSize CheckTypeSize
=============
Check sizeof a type
```
CHECK_TYPE_SIZE(TYPE VARIABLE [BUILTIN_TYPES_ONLY]
[LANGUAGE <language>])
```
Check if the type exists and determine its size. On return, “HAVE\_${VARIABLE}” holds the existence of the type, and “${VARIABLE}” holds one of the following:
```
<size> = type has non-zero size <size>
"0" = type has arch-dependent size (see below)
"" = type does not exist
```
Both `HAVE_${VARIABLE}` and `${VARIABLE}` will be created as internal cache variables.
Furthermore, the variable “${VARIABLE}\_CODE” holds C preprocessor code to define the macro “${VARIABLE}” to the size of the type, or leave the macro undefined if the type does not exist.
The variable “${VARIABLE}” may be “0” when CMAKE\_OSX\_ARCHITECTURES has multiple architectures for building OS X universal binaries. This indicates that the type size varies across architectures. In this case “${VARIABLE}\_CODE” contains C preprocessor tests mapping from each architecture macro to the corresponding type size. The list of architecture macros is stored in “${VARIABLE}\_KEYS”, and the value for each key is stored in “${VARIABLE}-${KEY}”.
If the BUILTIN\_TYPES\_ONLY option is not given, the macro checks for headers <sys/types.h>, <stdint.h>, and <stddef.h>, and saves results in HAVE\_SYS\_TYPES\_H, HAVE\_STDINT\_H, and HAVE\_STDDEF\_H. The type size check automatically includes the available headers, thus supporting checks of types defined in the headers.
If LANGUAGE is set, the specified compiler will be used to perform the check. Acceptable values are C and CXX
Despite the name of the macro you may use it to check the size of more complex expressions, too. To check e.g. for the size of a struct member you can do something like this:
```
check_type_size("((struct something*)0)->member" SIZEOF_MEMBER)
```
The following variables may be set before calling this macro to modify the way the check is run:
```
CMAKE_REQUIRED_FLAGS = string of compile command line flags
CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
CMAKE_REQUIRED_INCLUDES = list of include directories
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
CMAKE_REQUIRED_QUIET = execute quietly without messages
CMAKE_EXTRA_INCLUDE_FILES = list of extra headers to include
```
cmake FindSDL_net FindSDL\_net
============
Locate SDL\_net library
This module defines:
```
SDL_NET_LIBRARIES, the name of the library to link against
SDL_NET_INCLUDE_DIRS, where to find the headers
SDL_NET_FOUND, if false, do not try to link against
SDL_NET_VERSION_STRING - human-readable string containing the version of SDL_net
```
For backward compatibility the following variables are also set:
```
SDLNET_LIBRARY (same value as SDL_NET_LIBRARIES)
SDLNET_INCLUDE_DIR (same value as SDL_NET_INCLUDE_DIRS)
SDLNET_FOUND (same value as SDL_NET_FOUND)
```
$SDLDIR is an environment variable that would correspond to the ./configure –prefix=$SDLDIR used in building SDL.
Created by Eric Wing. This was influenced by the FindSDL.cmake module, but with modifications to recognize OS X frameworks and additional Unix paths (FreeBSD, etc).
cmake FindIntl FindIntl
========
Find the Gettext libintl headers and libraries.
This module reports information about the Gettext libintl installation in several variables. General variables:
```
Intl_FOUND - true if the libintl headers and libraries were found
Intl_INCLUDE_DIRS - the directory containing the libintl headers
Intl_LIBRARIES - libintl libraries to be linked
```
The following cache variables may also be set:
```
Intl_INCLUDE_DIR - the directory containing the libintl headers
Intl_LIBRARY - the libintl library (if any)
```
Note
On some platforms, such as Linux with GNU libc, the gettext functions are present in the C standard library and libintl is not required. `Intl_LIBRARIES` will be empty in this case.
Note
If you wish to use the Gettext tools (`msgmerge`, `msgfmt`, etc.), use [`FindGettext`](findgettext#module:FindGettext "FindGettext").
cmake FindSubversion FindSubversion
==============
Extract information from a subversion working copy
The module defines the following variables:
```
Subversion_SVN_EXECUTABLE - path to svn command line client
Subversion_VERSION_SVN - version of svn command line client
Subversion_FOUND - true if the command line client was found
SUBVERSION_FOUND - same as Subversion_FOUND, set for compatibility reasons
```
The minimum required version of Subversion can be specified using the standard syntax, e.g. find\_package(Subversion 1.4)
If the command line client executable is found two macros are defined:
```
Subversion_WC_INFO(<dir> <var-prefix>)
Subversion_WC_LOG(<dir> <var-prefix>)
```
Subversion\_WC\_INFO extracts information of a subversion working copy at a given location. This macro defines the following variables:
```
<var-prefix>_WC_URL - url of the repository (at <dir>)
<var-prefix>_WC_ROOT - root url of the repository
<var-prefix>_WC_REVISION - current revision
<var-prefix>_WC_LAST_CHANGED_AUTHOR - author of last commit
<var-prefix>_WC_LAST_CHANGED_DATE - date of last commit
<var-prefix>_WC_LAST_CHANGED_REV - revision of last commit
<var-prefix>_WC_INFO - output of command `svn info <dir>'
```
Subversion\_WC\_LOG retrieves the log message of the base revision of a subversion working copy at a given location. This macro defines the variable:
```
<var-prefix>_LAST_CHANGED_LOG - last log of base revision
```
Example usage:
```
find_package(Subversion)
if(SUBVERSION_FOUND)
Subversion_WC_INFO(${PROJECT_SOURCE_DIR} Project)
message("Current revision is ${Project_WC_REVISION}")
Subversion_WC_LOG(${PROJECT_SOURCE_DIR} Project)
message("Last changed log is ${Project_LAST_CHANGED_LOG}")
endif()
```
cmake FindosgPresentation FindosgPresentation
===================
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgPresentation This module defines
OSGPRESENTATION\_FOUND - Was osgPresentation found? OSGPRESENTATION\_INCLUDE\_DIR - Where to find the headers OSGPRESENTATION\_LIBRARIES - The libraries to link for osgPresentation (use this)
OSGPRESENTATION\_LIBRARY - The osgPresentation library OSGPRESENTATION\_LIBRARY\_DEBUG - The osgPresentation debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing. Modified to work with osgPresentation by Robert Osfield, January 2012.
| programming_docs |
cmake FindLAPACK FindLAPACK
==========
Find LAPACK library
This module finds an installed fortran library that implements the LAPACK linear-algebra interface (see <http://www.netlib.org/lapack/>).
The approach follows that taken for the autoconf macro file, acx\_lapack.m4 (distributed at <http://ac-archive.sourceforge.net/ac-archive/acx_lapack.html>).
This module sets the following variables:
```
LAPACK_FOUND - set to true if a library implementing the LAPACK interface
is found
LAPACK_LINKER_FLAGS - uncached list of required linker flags (excluding -l
and -L).
LAPACK_LIBRARIES - uncached list of libraries (using full path name) to
link against to use LAPACK
LAPACK95_LIBRARIES - uncached list of libraries (using full path name) to
link against to use LAPACK95
LAPACK95_FOUND - set to true if a library implementing the LAPACK f95
interface is found
BLA_STATIC if set on this determines what kind of linkage we do (static)
BLA_VENDOR if set checks only the specified vendor, if not set checks
all the possibilities
BLA_F95 if set on tries to find the f95 interfaces for BLAS/LAPACK
```
List of vendors (BLA\_VENDOR) valid in this module:
* Intel(mkl)
* OpenBLAS
* ACML
* Apple
* NAS
* Generic
cmake CheckCSourceRuns CheckCSourceRuns
================
Check if the given C source code compiles and runs.
CHECK\_C\_SOURCE\_RUNS(<code> <var>)
```
<code> - source code to try to compile
<var> - variable to store the result
(1 for success, empty for failure)
Will be created as an internal cache variable.
```
The following variables may be set before calling this macro to modify the way the check is run:
```
CMAKE_REQUIRED_FLAGS = string of compile command line flags
CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
CMAKE_REQUIRED_INCLUDES = list of include directories
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
CMAKE_REQUIRED_QUIET = execute quietly without messages
```
cmake FindPerl FindPerl
========
Find perl
this module looks for Perl
```
PERL_EXECUTABLE - the full path to perl
PERL_FOUND - If false, don't attempt to use perl.
PERL_VERSION_STRING - version of perl found (since CMake 2.8.8)
```
cmake FindGnuTLS FindGnuTLS
==========
Try to find the GNU Transport Layer Security library (gnutls)
Once done this will define
```
GNUTLS_FOUND - System has gnutls
GNUTLS_INCLUDE_DIR - The gnutls include directory
GNUTLS_LIBRARIES - The libraries needed to use gnutls
GNUTLS_DEFINITIONS - Compiler switches required for using gnutls
```
cmake CMakePackageConfigHelpers CMakePackageConfigHelpers
=========================
Helpers functions for creating config files that can be included by other projects to find and use a package.
Adds the [`configure_package_config_file()`](#command:configure_package_config_file "configure_package_config_file") and [`write_basic_package_version_file()`](#command:write_basic_package_version_file "write_basic_package_version_file") commands.
Generating a Package Configuration File
---------------------------------------
`configure_package_config_file`
Create a config file for a project:
```
configure_package_config_file(<input> <output>
INSTALL_DESTINATION <path>
[PATH_VARS <var1> <var2> ... <varN>]
[NO_SET_AND_CHECK_MACRO]
[NO_CHECK_REQUIRED_COMPONENTS_MACRO]
[INSTALL_PREFIX <path>]
)
```
`configure_package_config_file()` should be used instead of the plain [`configure_file()`](../command/configure_file#command:configure_file "configure_file") command when creating the `<Name>Config.cmake` or `<Name>-config.cmake` file for installing a project or library. It helps making the resulting package relocatable by avoiding hardcoded paths in the installed `Config.cmake` file.
In a `FooConfig.cmake` file there may be code like this to make the install destinations know to the using project:
```
set(FOO_INCLUDE_DIR "@CMAKE_INSTALL_FULL_INCLUDEDIR@" )
set(FOO_DATA_DIR "@CMAKE_INSTALL_PREFIX@/@RELATIVE_DATA_INSTALL_DIR@" )
set(FOO_ICONS_DIR "@CMAKE_INSTALL_PREFIX@/share/icons" )
#...logic to determine installedPrefix from the own location...
set(FOO_CONFIG_DIR "${installedPrefix}/@CONFIG_INSTALL_DIR@" )
```
All 4 options shown above are not sufficient, since the first 3 hardcode the absolute directory locations, and the 4th case works only if the logic to determine the `installedPrefix` is correct, and if `CONFIG_INSTALL_DIR` contains a relative path, which in general cannot be guaranteed. This has the effect that the resulting `FooConfig.cmake` file would work poorly under Windows and OSX, where users are used to choose the install location of a binary package at install time, independent from how [`CMAKE_INSTALL_PREFIX`](../variable/cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") was set at build/cmake time.
Using `configure_package_config_file` helps. If used correctly, it makes the resulting `FooConfig.cmake` file relocatable. Usage:
1. write a `FooConfig.cmake.in` file as you are used to
2. insert a line containing only the string `@PACKAGE_INIT@`
3. instead of `set(FOO_DIR "@SOME_INSTALL_DIR@")`, use `set(FOO_DIR "@PACKAGE_SOME_INSTALL_DIR@")` (this must be after the `@PACKAGE_INIT@` line)
4. instead of using the normal [`configure_file()`](../command/configure_file#command:configure_file "configure_file"), use `configure_package_config_file()`
The `<input>` and `<output>` arguments are the input and output file, the same way as in [`configure_file()`](../command/configure_file#command:configure_file "configure_file").
The `<path>` given to `INSTALL_DESTINATION` must be the destination where the `FooConfig.cmake` file will be installed to. This path can either be absolute, or relative to the `INSTALL_PREFIX` path.
The variables `<var1>` to `<varN>` given as `PATH_VARS` are the variables which contain install destinations. For each of them the macro will create a helper variable `PACKAGE_<var...>`. These helper variables must be used in the `FooConfig.cmake.in` file for setting the installed location. They are calculated by `configure_package_config_file` so that they are always relative to the installed location of the package. This works both for relative and also for absolute locations. For absolute locations it works only if the absolute location is a subdirectory of `INSTALL_PREFIX`.
If the `INSTALL_PREFIX` argument is passed, this is used as base path to calculate all the relative paths. The `<path>` argument must be an absolute path. If this argument is not passed, the [`CMAKE_INSTALL_PREFIX`](../variable/cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") variable will be used instead. The default value is good when generating a FooConfig.cmake file to use your package from the install tree. When generating a FooConfig.cmake file to use your package from the build tree this option should be used.
By default `configure_package_config_file` also generates two helper macros, `set_and_check()` and `check_required_components()` into the `FooConfig.cmake` file.
`set_and_check()` should be used instead of the normal `set()` command for setting directories and file locations. Additionally to setting the variable it also checks that the referenced file or directory actually exists and fails with a `FATAL_ERROR` otherwise. This makes sure that the created `FooConfig.cmake` file does not contain wrong references. When using the `NO_SET_AND_CHECK_MACRO`, this macro is not generated into the `FooConfig.cmake` file.
`check_required_components(<package_name>)` should be called at the end of the `FooConfig.cmake` file if the package supports components. This macro checks whether all requested, non-optional components have been found, and if this is not the case, sets the `Foo_FOUND` variable to `FALSE`, so that the package is considered to be not found. It does that by testing the `Foo_<Component>_FOUND` variables for all requested required components. When using the `NO_CHECK_REQUIRED_COMPONENTS_MACRO` option, this macro is not generated into the `FooConfig.cmake` file.
For an example see below the documentation for [`write_basic_package_version_file()`](#command:write_basic_package_version_file "write_basic_package_version_file").
Generating a Package Version File
---------------------------------
`write_basic_package_version_file`
Create a version file for a project:
```
write_basic_package_version_file(<filename>
[VERSION <major.minor.patch>]
COMPATIBILITY <AnyNewerVersion|SameMajorVersion|ExactVersion> )
```
Writes a file for use as `<package>ConfigVersion.cmake` file to `<filename>`. See the documentation of [`find_package()`](../command/find_package#command:find_package "find_package") for details on this.
`<filename>` is the output filename, it should be in the build tree. `<major.minor.patch>` is the version number of the project to be installed.
If no `VERSION` is given, the [`PROJECT_VERSION`](../variable/project_version#variable:PROJECT_VERSION "PROJECT_VERSION") variable is used. If this hasn’t been set, it errors out.
The `COMPATIBILITY` mode `AnyNewerVersion` means that the installed package version will be considered compatible if it is newer or exactly the same as the requested version. This mode should be used for packages which are fully backward compatible, also across major versions. If `SameMajorVersion` is used instead, then the behaviour differs from `AnyNewerVersion` in that the major version number must be the same as requested, e.g. version 2.0 will not be considered compatible if 1.0 is requested. This mode should be used for packages which guarantee backward compatibility within the same major version. If `ExactVersion` is used, then the package is only considered compatible if the requested version matches exactly its own version number (not considering the tweak version). For example, version 1.2.3 of a package is only considered compatible to requested version 1.2.3. This mode is for packages without compatibility guarantees. If your project has more elaborated version matching rules, you will need to write your own custom `ConfigVersion.cmake` file instead of using this macro.
Internally, this macro executes [`configure_file()`](../command/configure_file#command:configure_file "configure_file") to create the resulting version file. Depending on the `COMPATIBLITY`, either the file `BasicConfigVersion-SameMajorVersion.cmake.in` or `BasicConfigVersion-AnyNewerVersion.cmake.in` is used. Please note that these two files are internal to CMake and you should not call [`configure_file()`](../command/configure_file#command:configure_file "configure_file") on them yourself, but they can be used as starting point to create more sophisticted custom `ConfigVersion.cmake` files.
Example Generating Package Files
--------------------------------
Example using both [`configure_package_config_file()`](#command:configure_package_config_file "configure_package_config_file") and `write_basic_package_version_file()`:
`CMakeLists.txt`:
```
set(INCLUDE_INSTALL_DIR include/ ... CACHE )
set(LIB_INSTALL_DIR lib/ ... CACHE )
set(SYSCONFIG_INSTALL_DIR etc/foo/ ... CACHE )
#...
include(CMakePackageConfigHelpers)
configure_package_config_file(FooConfig.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
INSTALL_DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake
PATH_VARS INCLUDE_INSTALL_DIR SYSCONFIG_INSTALL_DIR)
write_basic_package_version_file(
${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
VERSION 1.2.3
COMPATIBILITY SameMajorVersion )
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake )
```
`FooConfig.cmake.in`:
```
set(FOO_VERSION x.y.z)
...
@PACKAGE_INIT@
...
set_and_check(FOO_INCLUDE_DIR "@PACKAGE_INCLUDE_INSTALL_DIR@")
set_and_check(FOO_SYSCONFIG_DIR "@PACKAGE_SYSCONFIG_INSTALL_DIR@")
check_required_components(Foo)
```
cmake FindosgGA FindosgGA
=========
This is part of the Findosg\* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won’t do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn’t work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg\*.cmake modules.
Locate osgGA This module defines
OSGGA\_FOUND - Was osgGA found? OSGGA\_INCLUDE\_DIR - Where to find the headers OSGGA\_LIBRARIES - The libraries to link against for the osgGA (use this)
OSGGA\_LIBRARY - The osgGA library OSGGA\_LIBRARY\_DEBUG - The osgGA debug library
$OSGDIR is an environment variable that would correspond to the ./configure –prefix=$OSGDIR used in building osg.
Created by Eric Wing.
cmake CheckCXXCompilerFlag CheckCXXCompilerFlag
====================
Check whether the CXX compiler supports a given flag.
CHECK\_CXX\_COMPILER\_FLAG(<flag> <var>)
```
<flag> - the compiler flag
<var> - variable to store the result
```
This internally calls the check\_cxx\_source\_compiles macro and sets CMAKE\_REQUIRED\_DEFINITIONS to <flag>. See help for CheckCXXSourceCompiles for a listing of variables that can otherwise modify the build. The result only tells that the compiler does not give an error message when it encounters the flag. If the flag has any effect or even a specific one is beyond the scope of this module.
cmake FindKDE4 FindKDE4
========
Find KDE4 and provide all necessary variables and macros to compile software for it. It looks for KDE 4 in the following directories in the given order:
```
CMAKE_INSTALL_PREFIX
KDEDIRS
/opt/kde4
```
Please look in FindKDE4Internal.cmake and KDE4Macros.cmake for more information. They are installed with the KDE 4 libraries in $KDEDIRS/share/apps/cmake/modules/.
Author: Alexander Neundorf <[[email protected]](mailto:neundorf%40kde.org)>
cmake Findosg_functions Findosg\_functions
==================
This CMake file contains two macros to assist with searching for OSG libraries and nodekits. Please see FindOpenSceneGraph.cmake for full documentation.
cmake FindGettext FindGettext
===========
Find GNU gettext tools
This module looks for the GNU gettext tools. This module defines the following values:
```
GETTEXT_MSGMERGE_EXECUTABLE: the full path to the msgmerge tool.
GETTEXT_MSGFMT_EXECUTABLE: the full path to the msgfmt tool.
GETTEXT_FOUND: True if gettext has been found.
GETTEXT_VERSION_STRING: the version of gettext found (since CMake 2.8.8)
```
Additionally it provides the following macros:
GETTEXT\_CREATE\_TRANSLATIONS ( outputFile [ALL] file1 … fileN )
```
This will create a target "translations" which will convert the
given input po files into the binary output mo file. If the
ALL option is used, the translations will also be created when
building the default target.
```
GETTEXT\_PROCESS\_POT\_FILE( <potfile> [ALL] [INSTALL\_DESTINATION <destdir>] LANGUAGES <lang1> <lang2> … )
```
Process the given pot file to mo files.
If INSTALL_DESTINATION is given then automatically install rules will
be created, the language subdirectory will be taken into account
(by default use share/locale/).
If ALL is specified, the pot file is processed when building the all traget.
It creates a custom target "potfile".
```
GETTEXT\_PROCESS\_PO\_FILES( <lang> [ALL] [INSTALL\_DESTINATION <dir>] PO\_FILES <po1> <po2> … )
```
Process the given po files to mo files for the given language.
If INSTALL_DESTINATION is given then automatically install rules will
be created, the language subdirectory will be taken into account
(by default use share/locale/).
If ALL is specified, the po files are processed when building the all traget.
It creates a custom target "pofiles".
```
Note
If you wish to use the Gettext library (libintl), use [`FindIntl`](findintl#module:FindIntl "FindIntl").
cmake FindPhysFS FindPhysFS
==========
Locate PhysFS library This module defines PHYSFS\_LIBRARY, the name of the library to link against PHYSFS\_FOUND, if false, do not try to link to PHYSFS PHYSFS\_INCLUDE\_DIR, where to find physfs.h
$PHYSFSDIR is an environment variable that would correspond to the ./configure –prefix=$PHYSFSDIR used in building PHYSFS.
Created by Eric Wing.
cmake FindCABLE FindCABLE
=========
Find CABLE
This module finds if CABLE is installed and determines where the include files and libraries are. This code sets the following variables:
```
CABLE the path to the cable executable
CABLE_TCL_LIBRARY the path to the Tcl wrapper library
CABLE_INCLUDE_DIR the path to the include directory
```
To build Tcl wrappers, you should add shared library and link it to ${CABLE\_TCL\_LIBRARY}. You should also add ${CABLE\_INCLUDE\_DIR} as an include directory.
cmake FindBullet FindBullet
==========
Try to find the Bullet physics engine
```
This module defines the following variables
```
```
BULLET_FOUND - Was bullet found
BULLET_INCLUDE_DIRS - the Bullet include directories
BULLET_LIBRARIES - Link to this, by default it includes
all bullet components (Dynamics,
Collision, LinearMath, & SoftBody)
```
```
This module accepts the following variables
```
```
BULLET_ROOT - Can be set to bullet install path or Windows build path
```
cmake CTestUseLaunchers CTestUseLaunchers
=================
Set the RULE\_LAUNCH\_\* global properties when CTEST\_USE\_LAUNCHERS is on.
CTestUseLaunchers is automatically included when you include(CTest). However, it is split out into its own module file so projects can use the CTEST\_USE\_LAUNCHERS functionality independently.
To use launchers, set CTEST\_USE\_LAUNCHERS to ON in a ctest -S dashboard script, and then also set it in the cache of the configured project. Both cmake and ctest need to know the value of it for the launchers to work properly. CMake needs to know in order to generate proper build rules, and ctest, in order to produce the proper error and warning analysis.
For convenience, you may set the ENV variable CTEST\_USE\_LAUNCHERS\_DEFAULT in your ctest -S script, too. Then, as long as your CMakeLists uses include(CTest) or include(CTestUseLaunchers), it will use the value of the ENV variable to initialize a CTEST\_USE\_LAUNCHERS cache variable. This cache variable initialization only occurs if CTEST\_USE\_LAUNCHERS is not already defined. If CTEST\_USE\_LAUNCHERS is on in a ctest -S script the ctest\_configure command will add -DCTEST\_USE\_LAUNCHERS:BOOL=TRUE to the cmake command used to configure the project.
cmake TestForANSIStreamHeaders TestForANSIStreamHeaders
========================
Test for compiler support of ANSI stream headers iostream, etc.
check if the compiler supports the standard ANSI iostream header (without the .h)
```
CMAKE_NO_ANSI_STREAM_HEADERS - defined by the results
```
cmake FindQt3 FindQt3
=======
Locate Qt include paths and libraries
This module defines:
```
QT_INCLUDE_DIR - where to find qt.h, etc.
QT_LIBRARIES - the libraries to link against to use Qt.
QT_DEFINITIONS - definitions to use when
compiling code that uses Qt.
QT_FOUND - If false, don't try to use Qt.
QT_VERSION_STRING - the version of Qt found
```
If you need the multithreaded version of Qt, set QT\_MT\_REQUIRED to TRUE
Also defined, but not for general use are:
```
QT_MOC_EXECUTABLE, where to find the moc tool.
QT_UIC_EXECUTABLE, where to find the uic tool.
QT_QT_LIBRARY, where to find the Qt library.
QT_QTMAIN_LIBRARY, where to find the qtmain
library. This is only required by Qt3 on Windows.
```
| programming_docs |
cmake FindwxWidgets FindwxWidgets
=============
Find a wxWidgets (a.k.a., wxWindows) installation.
This module finds if wxWidgets is installed and selects a default configuration to use. wxWidgets is a modular library. To specify the modules that you will use, you need to name them as components to the package:
find\_package(wxWidgets COMPONENTS core base …)
There are two search branches: a windows style and a unix style. For windows, the following variables are searched for and set to defaults in case of multiple choices. Change them if the defaults are not desired (i.e., these are the only variables you should change to select a configuration):
```
wxWidgets_ROOT_DIR - Base wxWidgets directory
(e.g., C:/wxWidgets-2.6.3).
wxWidgets_LIB_DIR - Path to wxWidgets libraries
(e.g., C:/wxWidgets-2.6.3/lib/vc_lib).
wxWidgets_CONFIGURATION - Configuration to use
(e.g., msw, mswd, mswu, mswunivud, etc.)
wxWidgets_EXCLUDE_COMMON_LIBRARIES
- Set to TRUE to exclude linking of
commonly required libs (e.g., png tiff
jpeg zlib regex expat).
```
For unix style it uses the wx-config utility. You can select between debug/release, unicode/ansi, universal/non-universal, and static/shared in the QtDialog or ccmake interfaces by turning ON/OFF the following variables:
```
wxWidgets_USE_DEBUG
wxWidgets_USE_UNICODE
wxWidgets_USE_UNIVERSAL
wxWidgets_USE_STATIC
```
There is also a wxWidgets\_CONFIG\_OPTIONS variable for all other options that need to be passed to the wx-config utility. For example, to use the base toolkit found in the /usr/local path, set the variable (before calling the FIND\_PACKAGE command) as such:
```
set(wxWidgets_CONFIG_OPTIONS --toolkit=base --prefix=/usr)
```
The following are set after the configuration is done for both windows and unix style:
```
wxWidgets_FOUND - Set to TRUE if wxWidgets was found.
wxWidgets_INCLUDE_DIRS - Include directories for WIN32
i.e., where to find "wx/wx.h" and
"wx/setup.h"; possibly empty for unices.
wxWidgets_LIBRARIES - Path to the wxWidgets libraries.
wxWidgets_LIBRARY_DIRS - compile time link dirs, useful for
rpath on UNIX. Typically an empty string
in WIN32 environment.
wxWidgets_DEFINITIONS - Contains defines required to compile/link
against WX, e.g. WXUSINGDLL
wxWidgets_DEFINITIONS_DEBUG- Contains defines required to compile/link
against WX debug builds, e.g. __WXDEBUG__
wxWidgets_CXX_FLAGS - Include dirs and compiler flags for
unices, empty on WIN32. Essentially
"`wx-config --cxxflags`".
wxWidgets_USE_FILE - Convenience include file.
```
Sample usage:
```
# Note that for MinGW users the order of libs is important!
find_package(wxWidgets COMPONENTS net gl core base)
if(wxWidgets_FOUND)
include(${wxWidgets_USE_FILE})
# and for each of your dependent executable/library targets:
target_link_libraries(<YourTarget> ${wxWidgets_LIBRARIES})
endif()
```
If wxWidgets is required (i.e., not an optional part):
```
find_package(wxWidgets REQUIRED net gl core base)
include(${wxWidgets_USE_FILE})
# and for each of your dependent executable/library targets:
target_link_libraries(<YourTarget> ${wxWidgets_LIBRARIES})
```
cmake MACOSX_PACKAGE_LOCATION MACOSX\_PACKAGE\_LOCATION
=========================
Place a source file inside a Application Bundle ([`MACOSX_BUNDLE`](../prop_tgt/macosx_bundle#prop_tgt:MACOSX_BUNDLE "MACOSX_BUNDLE")), Core Foundation Bundle ([`BUNDLE`](../prop_tgt/bundle#prop_tgt:BUNDLE "BUNDLE")), or Framework Bundle ([`FRAMEWORK`](../prop_tgt/framework#prop_tgt:FRAMEWORK "FRAMEWORK")). It is applicable for OS X and iOS.
Executable targets with the [`MACOSX_BUNDLE`](../prop_tgt/macosx_bundle#prop_tgt:MACOSX_BUNDLE "MACOSX_BUNDLE") property set are built as OS X or iOS application bundles on Apple platforms. Shared library targets with the [`FRAMEWORK`](../prop_tgt/framework#prop_tgt:FRAMEWORK "FRAMEWORK") property set are built as OS X or iOS frameworks on Apple platforms. Module library targets with the [`BUNDLE`](../prop_tgt/bundle#prop_tgt:BUNDLE "BUNDLE") property set are built as OS X `CFBundle` bundles on Apple platforms. Source files listed in the target with this property set will be copied to a directory inside the bundle or framework content folder specified by the property value. For OS X Application Bundles the content folder is `<name>.app/Contents`. For OS X Frameworks the content folder is `<name>.framework/Versions/<version>`. For OS X CFBundles the content folder is `<name>.bundle/Contents` (unless the extension is changed). See the [`PUBLIC_HEADER`](../prop_tgt/public_header#prop_tgt:PUBLIC_HEADER "PUBLIC_HEADER"), [`PRIVATE_HEADER`](../prop_tgt/private_header#prop_tgt:PRIVATE_HEADER "PRIVATE_HEADER"), and [`RESOURCE`](../prop_tgt/resource#prop_tgt:RESOURCE "RESOURCE") target properties for specifying files meant for `Headers`, `PrivateHeaders`, or `Resources` directories.
If the specified location is equal to `Resources`, the resulting location will be the same as if the [`RESOURCE`](../prop_tgt/resource#prop_tgt:RESOURCE "RESOURCE") property had been used. If the specified location is a sub-folder of `Resources`, it will be placed into the respective sub-folder. Note: For iOS Apple uses a flat bundle layout where no `Resources` folder exist. Therefore CMake strips the `Resources` folder name from the specified location.
cmake VS_XAML_TYPE VS\_XAML\_TYPE
==============
Mark a XAML source file as a different type than the default `Page`. The most common usage would be to set the default App.xaml file as ApplicationDefinition.
cmake XCODE_LAST_KNOWN_FILE_TYPE XCODE\_LAST\_KNOWN\_FILE\_TYPE
==============================
Set the Xcode `lastKnownFileType` attribute on its reference to a source file. CMake computes a default based on file extension but can be told explicitly with this property.
See also [`XCODE_EXPLICIT_FILE_TYPE`](xcode_explicit_file_type#prop_sf:XCODE_EXPLICIT_FILE_TYPE "XCODE_EXPLICIT_FILE_TYPE"), which is preferred over this property if set.
cmake XCODE_FILE_ATTRIBUTES XCODE\_FILE\_ATTRIBUTES
=======================
Add values to the Xcode `ATTRIBUTES` setting on its reference to a source file. Among other things, this can be used to set the role on a mig file:
```
set_source_files_properties(defs.mig
PROPERTIES
XCODE_FILE_ATTRIBUTES "Client;Server"
)
```
cmake EXTERNAL_OBJECT EXTERNAL\_OBJECT
================
If set to true then this is an object file.
If this property is set to true then the source file is really an object file and should not be compiled. It will still be linked into the target though.
cmake VS_SHADER_MODEL VS\_SHADER\_MODEL
=================
Specifies the shader model of a `.hlsl` source file. Some shader types can only be used with recent shader models
cmake ABSTRACT ABSTRACT
========
Is this source file an abstract class.
A property on a source file that indicates if the source file represents a class that is abstract. This only makes sense for languages that have a notion of an abstract class and it is only used by some tools that wrap classes into other languages.
cmake XCODE_EXPLICIT_FILE_TYPE XCODE\_EXPLICIT\_FILE\_TYPE
===========================
Set the Xcode `explicitFileType` attribute on its reference to a source file. CMake computes a default based on file extension but can be told explicitly with this property.
See also [`XCODE_LAST_KNOWN_FILE_TYPE`](xcode_last_known_file_type#prop_sf:XCODE_LAST_KNOWN_FILE_TYPE "XCODE_LAST_KNOWN_FILE_TYPE").
cmake COMPILE_DEFINITIONS COMPILE\_DEFINITIONS
====================
Preprocessor definitions for compiling a source file.
The COMPILE\_DEFINITIONS property may be set to a semicolon-separated list of preprocessor definitions using the syntax VAR or VAR=value. Function-style definitions are not supported. CMake will automatically escape the value correctly for the native build system (note that CMake language syntax may require escapes to specify some values). This property may be set on a per-configuration basis using the name COMPILE\_DEFINITIONS\_<CONFIG> where <CONFIG> is an upper-case name (ex. “COMPILE\_DEFINITIONS\_DEBUG”).
CMake will automatically drop some definitions that are not supported by the native build tool. Xcode does not support per-configuration definitions on source files.
Disclaimer: Most native build tools have poor support for escaping certain values. CMake has work-arounds for many cases but some values may just not be possible to pass correctly. If a value does not seem to be escaped correctly, do not attempt to work-around the problem by adding escape sequences to the value. Your work-around may break in a future version of CMake that has improved escape support. Instead consider defining the macro in a (configured) header file. Then report the limitation. Known limitations include:
```
# - broken almost everywhere
; - broken in VS IDE 7.0 and Borland Makefiles
, - broken in VS IDE
% - broken in some cases in NMake
& | - broken in some cases on MinGW
^ < > \" - broken in most Make tools on Windows
```
CMake does not reject these values outright because they do work in some cases. Use with caution.
cmake VS_DEPLOYMENT_LOCATION VS\_DEPLOYMENT\_LOCATION
========================
Specifies the deployment location for a content source file with a Windows Phone or Windows Store application when built with a Visual Studio generator. This property is only applicable when using [`VS_DEPLOYMENT_CONTENT`](vs_deployment_content#prop_sf:VS_DEPLOYMENT_CONTENT "VS_DEPLOYMENT_CONTENT"). The value represent the path relative to the app package and applies to all configurations.
cmake AUTORCC_OPTIONS AUTORCC\_OPTIONS
================
Additional options for `rcc` when using [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC")
This property holds additional command line options which will be used when `rcc` is executed during the build via [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC"), i.e. it is equivalent to the optional `OPTIONS` argument of the [`qt4_add_resources()`](../module/findqt4#module:FindQt4 "FindQt4") macro.
By default it is empty.
The options set on the `.qrc` source file may override [`AUTORCC_OPTIONS`](../prop_tgt/autorcc_options#prop_tgt:AUTORCC_OPTIONS "AUTORCC_OPTIONS") set on the target.
cmake COMPILE_FLAGS COMPILE\_FLAGS
==============
Additional flags to be added when compiling this source file.
These flags will be added to the list of compile flags when this source file builds. Use [`COMPILE_DEFINITIONS`](compile_definitions#prop_sf:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") to pass additional preprocessor definitions.
Contents of `COMPILE_FLAGS` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. However, [`Xcode`](https://cmake.org/cmake/help/v3.9/generator/Xcode.html#generator:Xcode "Xcode") does not support per-config per-source settings, so expressions that depend on the build configuration are not allowed with that generator.
cmake COMPILE_DEFINITIONS_<CONFIG> COMPILE\_DEFINITIONS\_<CONFIG>
==============================
Ignored. See CMake Policy [`CMP0043`](../policy/cmp0043#policy:CMP0043 "CMP0043").
Per-configuration preprocessor definitions on a source file.
This is the configuration-specific version of COMPILE\_DEFINITIONS. Note that Xcode does not support per-configuration source file flags so this property will be ignored by the Xcode generator.
cmake VS_COPY_TO_OUT_DIR VS\_COPY\_TO\_OUT\_DIR
======================
Sets the `<CopyToOutputDirectory>` tag for a source file in a Visual Studio project file. Valid values are `Never`, `Always` and `PreserveNewest`.
cmake AUTOUIC_OPTIONS AUTOUIC\_OPTIONS
================
Additional options for `uic` when using [`AUTOUIC`](../prop_tgt/autouic#prop_tgt:AUTOUIC "AUTOUIC")
This property holds additional command line options which will be used when `uic` is executed during the build via [`AUTOUIC`](../prop_tgt/autouic#prop_tgt:AUTOUIC "AUTOUIC"), i.e. it is equivalent to the optional `OPTIONS` argument of the [`qt4_wrap_ui()`](../module/findqt4#module:FindQt4 "FindQt4") macro.
By default it is empty.
The options set on the `.ui` source file may override [`AUTOUIC_OPTIONS`](../prop_tgt/autouic_options#prop_tgt:AUTOUIC_OPTIONS "AUTOUIC_OPTIONS") set on the target.
cmake OBJECT_OUTPUTS OBJECT\_OUTPUTS
===============
Additional outputs for a Makefile rule.
Additional outputs created by compilation of this source file. If any of these outputs is missing the object will be recompiled. This is supported only on Makefile generators and will be ignored on other generators.
cmake HEADER_FILE_ONLY HEADER\_FILE\_ONLY
==================
Is this source file only a header file.
A property on a source file that indicates if the source file is a header file with no associated implementation. This is set automatically based on the file extension and is used by CMake to determine if certain dependency information should be computed.
By setting this property to `ON`, you can disable compilation of the given source file, even if it should be compiled because it is part of the library’s/executable’s sources.
This is useful if you have some source files which you somehow pre-process, and then add these pre-processed sources via [`add_library()`](../command/add_library#command:add_library "add_library") or [`add_executable()`](../command/add_executable#command:add_executable "add_executable"). Normally, in IDE, there would be no reference of the original sources, only of these pre-processed sources. So by setting this property for all the original source files to `ON`, and then either calling [`add_library()`](../command/add_library#command:add_library "add_library") or [`add_executable()`](../command/add_executable#command:add_executable "add_executable") while passing both the pre-processed sources and the original sources, or by using [`target_sources()`](../command/target_sources#command:target_sources "target_sources") to add original source files will do exactly what would one expect, i.e. the original source files would be visible in IDE, and will not be built.
cmake SKIP_AUTOMOC SKIP\_AUTOMOC
=============
Exclude the source file from [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") processing (for Qt projects).
For broader control see [`SKIP_AUTOGEN`](skip_autogen#prop_sf:SKIP_AUTOGEN "SKIP_AUTOGEN")
cmake VS_CSHARP_<tagname> VS\_CSHARP\_<tagname>
=====================
Visual Studio and CSharp source-file-specific configuration.
Tell the Visual Studio generator to set the source file tag `<tagname>` to a given value in the generated Visual Studio CSharp project. Ignored on other generators and languages. This property can be used to define dependencies between source files or set any other Visual Studio specific parameters.
Example usage:
```
set_source_files_property(<filename>
PROPERTIES
VS_CSHARP_DependentUpon <other file>
VS_CSHARP_SubType "Form")
```
cmake SKIP_AUTORCC SKIP\_AUTORCC
=============
Exclude the source file from [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC") processing (for Qt projects).
For broader control see [`SKIP_AUTOGEN`](skip_autogen#prop_sf:SKIP_AUTOGEN "SKIP_AUTOGEN")
cmake WRAP_EXCLUDE WRAP\_EXCLUDE
=============
Exclude this source file from any code wrapping techniques.
Some packages can wrap source files into alternate languages to provide additional functionality. For example, C++ code can be wrapped into Java or Python etc using SWIG etc. If WRAP\_EXCLUDE is set to true (1 etc) that indicates that this source file should not be wrapped.
cmake SKIP_AUTOUIC SKIP\_AUTOUIC
=============
Exclude the source file from [`AUTOUIC`](../prop_tgt/autouic#prop_tgt:AUTOUIC "AUTOUIC") processing (for Qt projects).
For broader control see [`SKIP_AUTOGEN`](skip_autogen#prop_sf:SKIP_AUTOGEN "SKIP_AUTOGEN")
cmake VS_RESOURCE_GENERATOR VS\_RESOURCE\_GENERATOR
=======================
This property allows to specify the resource generator to be used on this file. It defaults to `PublicResXFileCodeGenerator` if not set.
This property only applies to C# projects.
cmake SYMBOLIC SYMBOLIC
========
Is this just a name for a rule.
If SYMBOLIC (boolean) is set to true the build system will be informed that the source file is not actually created on disk but instead used as a symbolic name for a build rule.
cmake KEEP_EXTENSION KEEP\_EXTENSION
===============
Make the output file have the same extension as the source file.
If this property is set then the file extension of the output file will be the same as that of the source file. Normally the output file extension is computed based on the language of the source file, for example .cxx will go to a .o extension.
cmake OBJECT_DEPENDS OBJECT\_DEPENDS
===============
Additional files on which a compiled object file depends.
Specifies a [;-list](../manual/cmake-language.7#cmake-language-lists) of full-paths to files on which any object files compiled from this source file depend. On [Makefile Generators](../manual/cmake-generators.7#makefile-generators) and the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator an object file will be recompiled if any of the named files is newer than it. [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators) and the [`Xcode`](https://cmake.org/cmake/help/v3.9/generator/Xcode.html#generator:Xcode "Xcode") generator cannot implement such compilation dependencies.
This property need not be used to specify the dependency of a source file on a generated header file that it includes. Although the property was originally introduced for this purpose, it is no longer necessary. If the generated header file is created by a custom command in the same target as the source file, the automatic dependency scanning process will recognize the dependency. If the generated header file is created by another target, an inter-target dependency should be created with the [`add_dependencies()`](../command/add_dependencies#command:add_dependencies "add_dependencies") command (if one does not already exist due to linking relationships).
cmake LOCATION LOCATION
========
The full path to a source file.
A read only property on a SOURCE FILE that contains the full path to the source file.
cmake VS_DEPLOYMENT_CONTENT VS\_DEPLOYMENT\_CONTENT
=======================
Mark a source file as content for deployment with a Windows Phone or Windows Store application when built with a Visual Studio generator. The value must evaluate to either `1` or `0` and may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") to make the choice based on the build configuration. The `.vcxproj` file entry for the source file will be marked either `DeploymentContent` or `ExcludedFromBuild` for values `1` and `0`, respectively.
cmake LANGUAGE LANGUAGE
========
What programming language is the file.
A property that can be set to indicate what programming language the source file is. If it is not set the language is determined based on the file extension. Typical values are CXX C etc. Setting this property for a file means this file will be compiled. Do not set this for headers or files that should not be compiled.
| programming_docs |
cmake GENERATED GENERATED
=========
Is this source file generated as part of the build process.
If a source file is generated by the build process CMake will handle it differently in terms of dependency checking etc. Otherwise having a non-existent source file could create problems.
cmake Fortran_FORMAT Fortran\_FORMAT
===============
Set to FIXED or FREE to indicate the Fortran source layout.
This property tells CMake whether a given Fortran source file uses fixed-format or free-format. CMake will pass the corresponding format flag to the compiler. Consider using the target-wide Fortran\_FORMAT property if all source files in a target share the same format.
cmake LABELS LABELS
======
Specify a list of text labels associated with a source file.
This property has meaning only when the source file is listed in a target whose LABELS property is also set. No other semantics are currently specified.
cmake SKIP_AUTOGEN SKIP\_AUTOGEN
=============
Exclude the source file from [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC"), [`AUTOUIC`](../prop_tgt/autouic#prop_tgt:AUTOUIC "AUTOUIC") and [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC") processing (for Qt projects).
For finer control see [`SKIP_AUTOMOC`](skip_automoc#prop_sf:SKIP_AUTOMOC "SKIP_AUTOMOC"), [`SKIP_AUTOUIC`](skip_autouic#prop_sf:SKIP_AUTOUIC "SKIP_AUTOUIC") and [`SKIP_AUTORCC`](skip_autorcc#prop_sf:SKIP_AUTORCC "SKIP_AUTORCC").
cmake VS_INCLUDE_IN_VSIX VS\_INCLUDE\_IN\_VSIX
=====================
Boolean property to specify if the file should be included within a VSIX extension package. This is needed for development of Visual Studio extensions.
cmake VS_SHADER_ENTRYPOINT VS\_SHADER\_ENTRYPOINT
======================
Specifies the name of the entry point for the shader of a `.hlsl` source file.
cmake VS_TOOL_OVERRIDE VS\_TOOL\_OVERRIDE
==================
Override the default Visual Studio tool that will be applied to the source file with a new tool not based on the extension of the file.
cmake IMPORTED_LINK_DEPENDENT_LIBRARIES_<CONFIG> IMPORTED\_LINK\_DEPENDENT\_LIBRARIES\_<CONFIG>
==============================================
<CONFIG>-specific version of IMPORTED\_LINK\_DEPENDENT\_LIBRARIES.
Configuration names correspond to those provided by the project from which the target is imported. If set, this property completely overrides the generic property for the named configuration.
cmake COMPILE_PDB_NAME_<CONFIG> COMPILE\_PDB\_NAME\_<CONFIG>
============================
Per-configuration output name for the MS debug symbol `.pdb` file generated by the compiler while building source files.
This is the configuration-specific version of [`COMPILE_PDB_NAME`](compile_pdb_name#prop_tgt:COMPILE_PDB_NAME "COMPILE_PDB_NAME").
Note
The compiler-generated program database files are specified by the `/Fd` compiler flag and are not the same as linker-generated program database files specified by the `/pdb` linker flag. Use the [`PDB_NAME_<CONFIG>`](# "PDB_NAME_<CONFIG>") property to specify the latter.
cmake IMPLICIT_DEPENDS_INCLUDE_TRANSFORM IMPLICIT\_DEPENDS\_INCLUDE\_TRANSFORM
=====================================
Specify #include line transforms for dependencies in a target.
This property specifies rules to transform macro-like #include lines during implicit dependency scanning of C and C++ source files. The list of rules must be semicolon-separated with each entry of the form “A\_MACRO(%)=value-with-%” (the % must be literal). During dependency scanning occurrences of A\_MACRO(…) on #include lines will be replaced by the value given with the macro argument substituted for ‘%’. For example, the entry
```
MYDIR(%)=<mydir/%>
```
will convert lines of the form
```
#include MYDIR(myheader.h)
```
to
```
#include <mydir/myheader.h>
```
allowing the dependency to be followed.
This property applies to sources in the target on which it is set.
cmake LINK_FLAGS_<CONFIG> LINK\_FLAGS\_<CONFIG>
=====================
Per-configuration linker flags for a target.
This is the configuration-specific version of LINK\_FLAGS.
cmake OSX_ARCHITECTURES_<CONFIG> OSX\_ARCHITECTURES\_<CONFIG>
============================
Per-configuration OS X and iOS binary architectures for a target.
This property is the configuration-specific version of [`OSX_ARCHITECTURES`](osx_architectures#prop_tgt:OSX_ARCHITECTURES "OSX_ARCHITECTURES").
cmake MACOSX_BUNDLE_INFO_PLIST MACOSX\_BUNDLE\_INFO\_PLIST
===========================
Specify a custom `Info.plist` template for a OS X and iOS Application Bundle.
An executable target with [`MACOSX_BUNDLE`](macosx_bundle#prop_tgt:MACOSX_BUNDLE "MACOSX_BUNDLE") enabled will be built as an application bundle on OS X. By default its `Info.plist` file is created by configuring a template called `MacOSXBundleInfo.plist.in` located in the [`CMAKE_MODULE_PATH`](../variable/cmake_module_path#variable:CMAKE_MODULE_PATH "CMAKE_MODULE_PATH"). This property specifies an alternative template file name which may be a full path.
The following target properties may be set to specify content to be configured into the file:
`MACOSX_BUNDLE_BUNDLE_NAME` Sets `CFBundleName`.
`MACOSX_BUNDLE_BUNDLE_VERSION` Sets `CFBundleVersion`.
`MACOSX_BUNDLE_COPYRIGHT` Sets `NSHumanReadableCopyright`.
`MACOSX_BUNDLE_GUI_IDENTIFIER` Sets `CFBundleIdentifier`.
`MACOSX_BUNDLE_ICON_FILE` Sets `CFBundleIconFile`.
`MACOSX_BUNDLE_INFO_STRING` Sets `CFBundleGetInfoString`.
`MACOSX_BUNDLE_LONG_VERSION_STRING` Sets `CFBundleLongVersionString`.
`MACOSX_BUNDLE_SHORT_VERSION_STRING` Sets `CFBundleShortVersionString`. CMake variables of the same name may be set to affect all targets in a directory that do not have each specific property set. If a custom `Info.plist` is specified by this property it may of course hard-code all the settings instead of using the target properties.
cmake XCTEST XCTEST
======
This target is a XCTest CFBundle on the Mac.
This property will usually get set via the [`xctest_add_bundle()`](../module/findxctest#command:xctest_add_bundle "xctest_add_bundle") macro in [`FindXCTest`](../module/findxctest#module:FindXCTest "FindXCTest") module.
If a module library target has this property set to true it will be built as a CFBundle when built on the Mac. It will have the directory structure required for a CFBundle.
This property depends on [`BUNDLE`](bundle#prop_tgt:BUNDLE "BUNDLE") to be effective.
cmake LINK_INTERFACE_LIBRARIES_<CONFIG> LINK\_INTERFACE\_LIBRARIES\_<CONFIG>
====================================
Per-configuration list of public interface libraries for a target.
This is the configuration-specific version of [`LINK_INTERFACE_LIBRARIES`](link_interface_libraries#prop_tgt:LINK_INTERFACE_LIBRARIES "LINK_INTERFACE_LIBRARIES"). If set, this property completely overrides the generic property for the named configuration.
This property is overridden by the [`INTERFACE_LINK_LIBRARIES`](interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES") property if policy [`CMP0022`](../policy/cmp0022#policy:CMP0022 "CMP0022") is `NEW`.
This property is deprecated. Use [`INTERFACE_LINK_LIBRARIES`](interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES") instead.
Creating Relocatable Packages
-----------------------------
Note that it is not advisable to populate the `LINK_INTERFACE_LIBRARIES_<CONFIG>` of a target with absolute paths to dependencies. That would hard-code into installed packages the library file paths for dependencies **as found on the machine the package was made on**.
See the [Creating Relocatable Packages](../manual/cmake-packages.7#creating-relocatable-packages) section of the [`cmake-packages(7)`](../manual/cmake-packages.7#manual:cmake-packages(7) "cmake-packages(7)") manual for discussion of additional care that must be taken when specifying usage requirements while creating packages for redistribution.
cmake ARCHIVE_OUTPUT_NAME ARCHIVE\_OUTPUT\_NAME
=====================
Output name for [ARCHIVE](../manual/cmake-buildsystem.7#archive-output-artifacts) target files.
This property specifies the base name for archive target files. It overrides [`OUTPUT_NAME`](output_name#prop_tgt:OUTPUT_NAME "OUTPUT_NAME") and [`OUTPUT_NAME_<CONFIG>`](# "OUTPUT_NAME_<CONFIG>") properties.
See also the [`ARCHIVE_OUTPUT_NAME_<CONFIG>`](# "ARCHIVE_OUTPUT_NAME_<CONFIG>") target property.
cmake HAS_CXX HAS\_CXX
========
Link the target using the C++ linker tool (obsolete).
This is equivalent to setting the LINKER\_LANGUAGE property to CXX. See that property’s documentation for details.
cmake C_EXTENSIONS C\_EXTENSIONS
=============
Boolean specifying whether compiler specific extensions are requested.
This property specifies whether compiler specific extensions should be used. For some compilers, this results in adding a flag such as `-std=gnu11` instead of `-std=c11` to the compile line. This property is `ON` by default. The basic C standard level is controlled by the [`C_STANDARD`](c_standard#prop_tgt:C_STANDARD "C_STANDARD") target property.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
This property is initialized by the value of the [`CMAKE_C_EXTENSIONS`](../variable/cmake_c_extensions#variable:CMAKE_C_EXTENSIONS "CMAKE_C_EXTENSIONS") variable if it is set when a target is created.
cmake PRE_INSTALL_SCRIPT PRE\_INSTALL\_SCRIPT
====================
Deprecated install support.
The PRE\_INSTALL\_SCRIPT and POST\_INSTALL\_SCRIPT properties are the old way to specify CMake scripts to run before and after installing a target. They are used only when the old INSTALL\_TARGETS command is used to install the target. Use the INSTALL command instead.
cmake VS_IOT_STARTUP_TASK VS\_IOT\_STARTUP\_TASK
======================
Visual Studio Windows 10 IoT Continuous Background Task
Specifies that the target should be compiled as a Continuous Background Task library.
cmake C_STANDARD_REQUIRED C\_STANDARD\_REQUIRED
=====================
Boolean describing whether the value of [`C_STANDARD`](c_standard#prop_tgt:C_STANDARD "C_STANDARD") is a requirement.
If this property is set to `ON`, then the value of the [`C_STANDARD`](c_standard#prop_tgt:C_STANDARD "C_STANDARD") target property is treated as a requirement. If this property is `OFF` or unset, the [`C_STANDARD`](c_standard#prop_tgt:C_STANDARD "C_STANDARD") target property is treated as optional and may “decay” to a previous standard if the requested is not available. For compilers that have no notion of a standard level, such as MSVC, this has no effect.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
This property is initialized by the value of the [`CMAKE_C_STANDARD_REQUIRED`](../variable/cmake_c_standard_required#variable:CMAKE_C_STANDARD_REQUIRED "CMAKE_C_STANDARD_REQUIRED") variable if it is set when a target is created.
cmake VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION VS\_WINDOWS\_TARGET\_PLATFORM\_MIN\_VERSION
===========================================
Visual Studio Windows Target Platform Minimum Version
For Windows 10. Specifies the minimum version of the OS that is being targeted. For example `10.0.10240.0`. If the value is not specified, the value of [`CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION`](../variable/cmake_vs_windows_target_platform_version#variable:CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION "CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION") will be used on WindowsStore projects otherwise the target platform minimum version will not be specified for the project.
cmake LINKER_LANGUAGE LINKER\_LANGUAGE
================
Specifies language whose compiler will invoke the linker.
For executables, shared libraries, and modules, this sets the language whose compiler is used to link the target (such as “C” or “CXX”). A typical value for an executable is the language of the source file providing the program entry point (main). If not set, the language with the highest linker preference value is the default. See documentation of CMAKE\_<LANG>\_LINKER\_PREFERENCE variables.
If this property is not set by the user, it will be calculated at generate-time by CMake.
cmake BUILD_WITH_INSTALL_RPATH BUILD\_WITH\_INSTALL\_RPATH
===========================
`BUILD_WITH_INSTALL_RPATH` is a boolean specifying whether to link the target in the build tree with the [`INSTALL_RPATH`](install_rpath#prop_tgt:INSTALL_RPATH "INSTALL_RPATH"). This takes precedence over [`SKIP_BUILD_RPATH`](skip_build_rpath#prop_tgt:SKIP_BUILD_RPATH "SKIP_BUILD_RPATH") and avoids the need for relinking before installation.
This property is initialized by the value of the [`CMAKE_BUILD_WITH_INSTALL_RPATH`](../variable/cmake_build_with_install_rpath#variable:CMAKE_BUILD_WITH_INSTALL_RPATH "CMAKE_BUILD_WITH_INSTALL_RPATH") variable if it is set when a target is created.
If policy [`CMP0068`](../policy/cmp0068#policy:CMP0068 "CMP0068") is not `NEW`, this property also controls use of [`INSTALL_NAME_DIR`](install_name_dir#prop_tgt:INSTALL_NAME_DIR "INSTALL_NAME_DIR") in the build tree on macOS. Either way, the [`BUILD_WITH_INSTALL_NAME_DIR`](build_with_install_name_dir#prop_tgt:BUILD_WITH_INSTALL_NAME_DIR "BUILD_WITH_INSTALL_NAME_DIR") target property takes precedence.
cmake VS_DOTNET_REFERENCES VS\_DOTNET\_REFERENCES
======================
Visual Studio managed project .NET references
Adds one or more semicolon-delimited .NET references to a generated Visual Studio project. For example, “System;System.Windows.Forms”.
cmake LINK_LIBRARIES LINK\_LIBRARIES
===============
List of direct link dependencies.
This property specifies the list of libraries or targets which will be used for linking. In addition to accepting values from the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command, values may be set directly on any target using the [`set_property()`](../command/set_property#command:set_property "set_property") command.
The value of this property is used by the generators to set the link libraries for the compiler.
Contents of `LINK_LIBRARIES` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake PROJECT_LABEL PROJECT\_LABEL
==============
Change the name of a target in an IDE.
Can be used to change the name of the target in an IDE like Visual Studio.
cmake VS_SCC_PROJECTNAME VS\_SCC\_PROJECTNAME
====================
Visual Studio Source Code Control Project.
Can be set to change the visual studio source code control project name property.
cmake INTERPROCEDURAL_OPTIMIZATION INTERPROCEDURAL\_OPTIMIZATION
=============================
Enable interprocedural optimization for a target.
If set to true, enables interprocedural optimizations if they are known to be supported by the compiler.
This property is initialized by the [`CMAKE_INTERPROCEDURAL_OPTIMIZATION`](../variable/cmake_interprocedural_optimization#variable:CMAKE_INTERPROCEDURAL_OPTIMIZATION "CMAKE_INTERPROCEDURAL_OPTIMIZATION") variable if it is set when a target is created.
cmake LINK_INTERFACE_MULTIPLICITY_<CONFIG> LINK\_INTERFACE\_MULTIPLICITY\_<CONFIG>
=======================================
Per-configuration repetition count for cycles of STATIC libraries.
This is the configuration-specific version of LINK\_INTERFACE\_MULTIPLICITY. If set, this property completely overrides the generic property for the named configuration.
cmake DEPLOYMENT_REMOTE_DIRECTORY DEPLOYMENT\_REMOTE\_DIRECTORY
=============================
Set the WinCE project `RemoteDirectory` in `DeploymentTool` and `RemoteExecutable` in `DebuggerTool` in `.vcproj` files generated by the [`Visual Studio 9 2008`](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%209%202008.html#generator:Visual%20Studio%209%202008 "Visual Studio 9 2008") and [`Visual Studio 8 2005`](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%208%202005.html#generator:Visual%20Studio%208%202005 "Visual Studio 8 2005") generators. This is useful when you want to debug on remote WinCE device. For example:
```
set_property(TARGET ${TARGET} PROPERTY
DEPLOYMENT_REMOTE_DIRECTORY "\\FlashStorage")
```
produces:
```
<DeploymentTool RemoteDirectory="\FlashStorage" ... />
<DebuggerTool RemoteExecutable="\FlashStorage\target_file" ... />
```
cmake VS_SDK_REFERENCES VS\_SDK\_REFERENCES
===================
Visual Studio project SDK references. Specify a [;-list](../manual/cmake-language.7#cmake-language-lists) of SDK references to be added to a generated Visual Studio project, e.g. `Microsoft.AdMediatorWindows81, Version=1.0`.
cmake EXCLUDE_FROM_ALL EXCLUDE\_FROM\_ALL
==================
Exclude the target from the all target.
A property on a target that indicates if the target is excluded from the default build target. If it is not, then with a Makefile for example typing make will cause this target to be built. The same concept applies to the default build of other generators. Installing a target with EXCLUDE\_FROM\_ALL set to true has undefined behavior.
cmake STATIC_LIBRARY_FLAGS STATIC\_LIBRARY\_FLAGS
======================
Extra flags to use when linking static libraries.
Extra flags to use when linking a static library.
cmake ANDROID_SECURE_PROPS_PATH ANDROID\_SECURE\_PROPS\_PATH
============================
Set the Android property that states the location of the secure properties file. This is a string property that contains the file path. This property is initialized by the value of the [`CMAKE_ANDROID_SECURE_PROPS_PATH`](../variable/cmake_android_secure_props_path#variable:CMAKE_ANDROID_SECURE_PROPS_PATH "CMAKE_ANDROID_SECURE_PROPS_PATH") variable if it is set when a target is created.
cmake PREFIX PREFIX
======
What comes before the library name.
A target property that can be set to override the prefix (such as “lib”) on a library name.
cmake VISIBILITY_INLINES_HIDDEN VISIBILITY\_INLINES\_HIDDEN
===========================
Whether to add a compile flag to hide symbols of inline functions
The `VISIBILITY_INLINES_HIDDEN` property determines whether a flag for hiding symbols for inline functions, such as `-fvisibility-inlines-hidden`, should be used when invoking the compiler. This property affects compilation in sources of all types of targets (subject to policy [`CMP0063`](../policy/cmp0063#policy:CMP0063 "CMP0063")).
This property is initialized by the value of the [`CMAKE_VISIBILITY_INLINES_HIDDEN`](../variable/cmake_visibility_inlines_hidden#variable:CMAKE_VISIBILITY_INLINES_HIDDEN "CMAKE_VISIBILITY_INLINES_HIDDEN") variable if it is set when a target is created.
cmake IOS_INSTALL_COMBINED IOS\_INSTALL\_COMBINED
======================
Build a combined (device and simulator) target when installing.
When this property is set to set to false (which is the default) then it will either be built with the device SDK or the simulator SDK depending on the SDK set. But if this property is set to true then the target will at install time also be built for the corresponding SDK and combined into one library.
This feature requires at least Xcode version 6.
cmake XCODE_EXPLICIT_FILE_TYPE XCODE\_EXPLICIT\_FILE\_TYPE
===========================
Set the Xcode `explicitFileType` attribute on its reference to a target. CMake computes a default based on target type but can be told explicitly with this property.
See also [`XCODE_PRODUCT_TYPE`](xcode_product_type#prop_tgt:XCODE_PRODUCT_TYPE "XCODE_PRODUCT_TYPE").
| programming_docs |
cmake AUTOGEN_TARGET_DEPENDS AUTOGEN\_TARGET\_DEPENDS
========================
Target dependencies of the corresponding `_autogen` target.
Targets which have their [`AUTOMOC`](automoc#prop_tgt:AUTOMOC "AUTOMOC") target `ON` have a corresponding `_autogen` target which is used to autogenerate generate moc files. As this `_autogen` target is created at generate-time, it is not possible to define dependencies of it, such as to create inputs for the `moc` executable.
The `AUTOGEN_TARGET_DEPENDS` target property can be set instead to a list of dependencies for the `_autogen` target. The buildsystem will be generated to depend on its contents.
See the [`cmake-qt(7)`](../manual/cmake-qt.7#manual:cmake-qt(7) "cmake-qt(7)") manual for more information on using CMake with Qt.
cmake TYPE TYPE
====
The type of the target.
This read-only property can be used to test the type of the given target. It will be one of STATIC\_LIBRARY, MODULE\_LIBRARY, SHARED\_LIBRARY, INTERFACE\_LIBRARY, EXECUTABLE or one of the internal target types.
cmake POST_INSTALL_SCRIPT POST\_INSTALL\_SCRIPT
=====================
Deprecated install support.
The PRE\_INSTALL\_SCRIPT and POST\_INSTALL\_SCRIPT properties are the old way to specify CMake scripts to run before and after installing a target. They are used only when the old INSTALL\_TARGETS command is used to install the target. Use the INSTALL command instead.
cmake ANDROID_PROGUARD ANDROID\_PROGUARD
=================
When this property is set to true that enables the ProGuard tool to shrink, optimize, and obfuscate the code by removing unused code and renaming classes, fields, and methods with semantically obscure names. This property is initialized by the value of the [`CMAKE_ANDROID_PROGUARD`](../variable/cmake_android_proguard#variable:CMAKE_ANDROID_PROGUARD "CMAKE_ANDROID_PROGUARD") variable if it is set when a target is created.
cmake POSITION_INDEPENDENT_CODE POSITION\_INDEPENDENT\_CODE
===========================
Whether to create a position-independent target
The `POSITION_INDEPENDENT_CODE` property determines whether position independent executables or shared libraries will be created. This property is `True` by default for `SHARED` and `MODULE` library targets and `False` otherwise. This property is initialized by the value of the [`CMAKE_POSITION_INDEPENDENT_CODE`](../variable/cmake_position_independent_code#variable:CMAKE_POSITION_INDEPENDENT_CODE "CMAKE_POSITION_INDEPENDENT_CODE") variable if it is set when a target is created.
cmake COMPILE_DEFINITIONS COMPILE\_DEFINITIONS
====================
Preprocessor definitions for compiling a target’s sources.
The `COMPILE_DEFINITIONS` property may be set to a semicolon-separated list of preprocessor definitions using the syntax `VAR` or `VAR=value`. Function-style definitions are not supported. CMake will automatically escape the value correctly for the native build system (note that CMake language syntax may require escapes to specify some values).
CMake will automatically drop some definitions that are not supported by the native build tool.
Disclaimer: Most native build tools have poor support for escaping certain values. CMake has work-arounds for many cases but some values may just not be possible to pass correctly. If a value does not seem to be escaped correctly, do not attempt to work-around the problem by adding escape sequences to the value. Your work-around may break in a future version of CMake that has improved escape support. Instead consider defining the macro in a (configured) header file. Then report the limitation. Known limitations include:
```
# - broken almost everywhere
; - broken in VS IDE 7.0 and Borland Makefiles
, - broken in VS IDE
% - broken in some cases in NMake
& | - broken in some cases on MinGW
^ < > \" - broken in most Make tools on Windows
```
CMake does not reject these values outright because they do work in some cases. Use with caution.
Contents of `COMPILE_DEFINITIONS` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
The corresponding [`COMPILE_DEFINITIONS_<CONFIG>`](# "COMPILE_DEFINITIONS_<CONFIG>") property may be set to specify per-configuration definitions. Generator expressions should be preferred instead of setting the alternative property.
cmake IMPORTED_LINK_INTERFACE_LIBRARIES IMPORTED\_LINK\_INTERFACE\_LIBRARIES
====================================
Transitive link interface of an IMPORTED target.
Set this to the list of libraries whose interface is included when an IMPORTED library target is linked to another target. The libraries will be included on the link line for the target. Unlike the LINK\_INTERFACE\_LIBRARIES property, this property applies to all imported target types, including STATIC libraries. This property is ignored for non-imported targets.
This property is ignored if the target also has a non-empty INTERFACE\_LINK\_LIBRARIES property.
This property is deprecated. Use INTERFACE\_LINK\_LIBRARIES instead.
cmake EXCLUDE_FROM_DEFAULT_BUILD_<CONFIG> EXCLUDE\_FROM\_DEFAULT\_BUILD\_<CONFIG>
=======================================
Per-configuration version of target exclusion from “Build Solution”.
This is the configuration-specific version of EXCLUDE\_FROM\_DEFAULT\_BUILD. If the generic EXCLUDE\_FROM\_DEFAULT\_BUILD is also set on a target, EXCLUDE\_FROM\_DEFAULT\_BUILD\_<CONFIG> takes precedence in configurations for which it has a value.
cmake PRIVATE_HEADER PRIVATE\_HEADER
===============
Specify private header files in a [`FRAMEWORK`](framework#prop_tgt:FRAMEWORK "FRAMEWORK") shared library target.
Shared library targets marked with the [`FRAMEWORK`](framework#prop_tgt:FRAMEWORK "FRAMEWORK") property generate frameworks on OS X, iOS and normal shared libraries on other platforms. This property may be set to a list of header files to be placed in the PrivateHeaders directory inside the framework folder. On non-Apple platforms these headers may be installed using the `PRIVATE_HEADER` option to the `install(TARGETS)` command.
cmake AUTOGEN_BUILD_DIR AUTOGEN\_BUILD\_DIR
===================
Directory where [`AUTOMOC`](automoc#prop_tgt:AUTOMOC "AUTOMOC"), [`AUTOUIC`](autouic#prop_tgt:AUTOUIC "AUTOUIC") and [`AUTORCC`](autorcc#prop_tgt:AUTORCC "AUTORCC") generate files for the target.
The directory is created on demand and automatically added to the [`ADDITIONAL_MAKE_CLEAN_FILES`](../prop_dir/additional_make_clean_files#prop_dir:ADDITIONAL_MAKE_CLEAN_FILES "ADDITIONAL_MAKE_CLEAN_FILES").
When unset or empty the directory `<dir>/<target-name>_autogen` is used where `<dir>` is [`CMAKE_CURRENT_BINARY_DIR`](../variable/cmake_current_binary_dir#variable:CMAKE_CURRENT_BINARY_DIR "CMAKE_CURRENT_BINARY_DIR") and `<target-name>` is [`NAME`](name#prop_tgt:NAME "NAME").
By default [`AUTOGEN_BUILD_DIR`](#prop_tgt:AUTOGEN_BUILD_DIR "AUTOGEN_BUILD_DIR") is unset.
See the [`cmake-qt(7)`](../manual/cmake-qt.7#manual:cmake-qt(7) "cmake-qt(7)") manual for more information on using CMake with Qt.
cmake ANDROID_NATIVE_LIB_DEPENDENCIES ANDROID\_NATIVE\_LIB\_DEPENDENCIES
==================================
Set the Android property that specifies the .so dependencies. This is a string property.
This property is initialized by the value of the [`CMAKE_ANDROID_NATIVE_LIB_DEPENDENCIES`](../variable/cmake_android_native_lib_dependencies#variable:CMAKE_ANDROID_NATIVE_LIB_DEPENDENCIES "CMAKE_ANDROID_NATIVE_LIB_DEPENDENCIES") variable if it is set when a target is created.
Contents of `ANDROID_NATIVE_LIB_DEPENDENCIES` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions.
cmake ARCHIVE_OUTPUT_NAME_<CONFIG> ARCHIVE\_OUTPUT\_NAME\_<CONFIG>
===============================
Per-configuration output name for [ARCHIVE](../manual/cmake-buildsystem.7#archive-output-artifacts) target files.
This is the configuration-specific version of the [`ARCHIVE_OUTPUT_NAME`](archive_output_name#prop_tgt:ARCHIVE_OUTPUT_NAME "ARCHIVE_OUTPUT_NAME") target property.
cmake CUDA_SEPARABLE_COMPILATION CUDA\_SEPARABLE\_COMPILATION
============================
CUDA only: Enables separate compilation of device code
If set this will enable separable compilation for all CUDA files for the given target.
For instance:
```
set_property(TARGET myexe PROPERTY CUDA_SEPARABLE_COMPILATION ON)
```
cmake ANDROID_JAR_DEPENDENCIES ANDROID\_JAR\_DEPENDENCIES
==========================
Set the Android property that specifies JAR dependencies. This is a string value property. This property is initialized by the value of the [`CMAKE_ANDROID_JAR_DEPENDENCIES`](../variable/cmake_android_jar_dependencies#variable:CMAKE_ANDROID_JAR_DEPENDENCIES "CMAKE_ANDROID_JAR_DEPENDENCIES") variable if it is set when a target is created.
cmake AUTORCC_OPTIONS AUTORCC\_OPTIONS
================
Additional options for `rcc` when using [`AUTORCC`](autorcc#prop_tgt:AUTORCC "AUTORCC")
This property holds additional command line options which will be used when `rcc` is executed during the build via [`AUTORCC`](autorcc#prop_tgt:AUTORCC "AUTORCC"), i.e. it is equivalent to the optional `OPTIONS` argument of the [`qt4_add_resources()`](../module/findqt4#module:FindQt4 "FindQt4") macro.
By default it is empty.
This property is initialized by the value of the [`CMAKE_AUTORCC_OPTIONS`](../variable/cmake_autorcc_options#variable:CMAKE_AUTORCC_OPTIONS "CMAKE_AUTORCC_OPTIONS") variable if it is set when a target is created.
The options set on the target may be overridden by [`AUTORCC_OPTIONS`](../prop_sf/autorcc_options#prop_sf:AUTORCC_OPTIONS "AUTORCC_OPTIONS") set on the `.qrc` source file.
See the [`cmake-qt(7)`](../manual/cmake-qt.7#manual:cmake-qt(7) "cmake-qt(7)") manual for more information on using CMake with Qt.
cmake ANDROID_PROGUARD_CONFIG_PATH ANDROID\_PROGUARD\_CONFIG\_PATH
===============================
Set the Android property that specifies the location of the ProGuard config file. Leave empty to use the default one. This a string property that contains the path to ProGuard config file. This property is initialized by the value of the [`CMAKE_ANDROID_PROGUARD_CONFIG_PATH`](../variable/cmake_android_proguard_config_path#variable:CMAKE_ANDROID_PROGUARD_CONFIG_PATH "CMAKE_ANDROID_PROGUARD_CONFIG_PATH") variable if it is set when a target is created.
cmake INTERFACE_COMPILE_DEFINITIONS INTERFACE\_COMPILE\_DEFINITIONS
===============================
List of public compile definitions requirements for a library.
Targets may populate this property to publish the compile definitions required to compile against the headers for the target. The [`target_compile_definitions()`](../command/target_compile_definitions#command:target_compile_definitions "target_compile_definitions") command populates this property with values given to the `PUBLIC` and `INTERFACE` keywords. Projects may also get and set the property directly.
When target dependencies are specified using [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries"), CMake will read this property from all target dependencies to determine the build properties of the consumer.
Contents of `INTERFACE_COMPILE_DEFINITIONS` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") -manual for more on defining buildsystem properties.
cmake COMPILE_FLAGS COMPILE\_FLAGS
==============
Additional flags to use when compiling this target’s sources.
The `COMPILE_FLAGS` property sets additional compiler flags used to build sources within the target. Use [`COMPILE_DEFINITIONS`](compile_definitions#prop_tgt:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") to pass additional preprocessor definitions.
This property is deprecated. Use the [`COMPILE_OPTIONS`](compile_options#prop_tgt:COMPILE_OPTIONS "COMPILE_OPTIONS") property or the command:`target_compile_options` command instead.
cmake COMPILE_DEFINITIONS_<CONFIG> COMPILE\_DEFINITIONS\_<CONFIG>
==============================
Ignored. See CMake Policy [`CMP0043`](../policy/cmp0043#policy:CMP0043 "CMP0043").
Per-configuration preprocessor definitions on a target.
This is the configuration-specific version of [`COMPILE_DEFINITIONS`](compile_definitions#prop_tgt:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") where `<CONFIG>` is an upper-case name (ex. `COMPILE_DEFINITIONS_DEBUG`).
Contents of `COMPILE_DEFINITIONS_<CONFIG>` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
Generator expressions should be preferred instead of setting this property.
cmake COMPATIBLE_INTERFACE_BOOL COMPATIBLE\_INTERFACE\_BOOL
===========================
Properties which must be compatible with their link interface
The `COMPATIBLE_INTERFACE_BOOL` property may contain a list of properties for this target which must be consistent when evaluated as a boolean with the `INTERFACE` variant of the property in all linked dependees. For example, if a property `FOO` appears in the list, then for each dependee, the `INTERFACE_FOO` property content in all of its dependencies must be consistent with each other, and with the `FOO` property in the depender.
Consistency in this sense has the meaning that if the property is set, then it must have the same boolean value as all others, and if the property is not set, then it is ignored.
Note that for each dependee, the set of properties specified in this property must not intersect with the set specified in any of the other [Compatible Interface Properties](../manual/cmake-buildsystem.7#compatible-interface-properties).
cmake VS_DESKTOP_EXTENSIONS_VERSION VS\_DESKTOP\_EXTENSIONS\_VERSION
================================
Visual Studio Windows 10 Desktop Extensions Version
Specifies the version of the Desktop Extensions that should be included in the target. For example `10.0.10240.0`. If the value is not specified, the Desktop Extensions will not be included. To use the same version of the extensions as the Windows 10 SDK that is being used, you can use the [`CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION`](../variable/cmake_vs_windows_target_platform_version#variable:CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION "CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION") variable.
cmake COMPATIBLE_INTERFACE_NUMBER_MAX COMPATIBLE\_INTERFACE\_NUMBER\_MAX
==================================
Properties whose maximum value from the link interface will be used.
The `COMPATIBLE_INTERFACE_NUMBER_MAX` property may contain a list of properties for this target whose maximum value may be read at generate time when evaluated in the `INTERFACE` variant of the property in all linked dependees. For example, if a property `FOO` appears in the list, then for each dependee, the `INTERFACE_FOO` property content in all of its dependencies will be compared with each other and with the `FOO` property in the depender. When reading the `FOO` property at generate time, the maximum value will be returned. If the property is not set, then it is ignored.
Note that for each dependee, the set of properties specified in this property must not intersect with the set specified in any of the other [Compatible Interface Properties](../manual/cmake-buildsystem.7#compatible-interface-properties).
cmake Fortran_MODULE_DIRECTORY Fortran\_MODULE\_DIRECTORY
==========================
Specify output directory for Fortran modules provided by the target.
If the target contains Fortran source files that provide modules and the compiler supports a module output directory this specifies the directory in which the modules will be placed. When this property is not set the modules will be placed in the build directory corresponding to the target’s source directory. If the variable CMAKE\_Fortran\_MODULE\_DIRECTORY is set when a target is created its value is used to initialize this property.
Note that some compilers will automatically search the module output directory for modules USEd during compilation but others will not. If your sources USE modules their location must be specified by INCLUDE\_DIRECTORIES regardless of this property.
cmake ANDROID_ARCH ANDROID\_ARCH
=============
When [Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio Edition](../manual/cmake-toolchains.7#cross-compiling-for-android-with-nvidia-nsight-tegra-visual-studio-edition), this property sets the Android target architecture.
This is a string property that could be set to the one of the following values:
* `armv7-a`: “ARMv7-A (armv7-a)”
* `armv7-a-hard`: “ARMv7-A, hard-float ABI (armv7-a)”
* `arm64-v8a`: “ARMv8-A, 64bit (arm64-v8a)”
* `x86`: “x86 (x86)”
* `x86_64`: “x86\_64 (x86\_64)”
This property is initialized by the value of the [`CMAKE_ANDROID_ARCH`](../variable/cmake_android_arch#variable:CMAKE_ANDROID_ARCH "CMAKE_ANDROID_ARCH") variable if it is set when a target is created.
cmake ANDROID_STL_TYPE ANDROID\_STL\_TYPE
==================
When [Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio Edition](../manual/cmake-toolchains.7#cross-compiling-for-android-with-nvidia-nsight-tegra-visual-studio-edition), this property specifies the type of STL support for the project. This is a string property that could set to the one of the following values:
`none` No C++ Support
`system` Minimal C++ without STL
`gabi++_static` GAbi++ Static
`gabi++_shared` GAbi++ Shared
`gnustl_static` GNU libstdc++ Static
`gnustl_shared` GNU libstdc++ Shared
`stlport_static` STLport Static
`stlport_shared` STLport Shared This property is initialized by the value of the [`CMAKE_ANDROID_STL_TYPE`](../variable/cmake_android_stl_type#variable:CMAKE_ANDROID_STL_TYPE "CMAKE_ANDROID_STL_TYPE") variable if it is set when a target is created.
cmake JOB_POOL_COMPILE JOB\_POOL\_COMPILE
==================
Ninja only: Pool used for compiling.
The number of parallel compile processes could be limited by defining pools with the global [`JOB_POOLS`](../prop_gbl/job_pools#prop_gbl:JOB_POOLS "JOB_POOLS") property and then specifying here the pool name.
For instance:
```
set_property(TARGET myexe PROPERTY JOB_POOL_COMPILE ten_jobs)
```
This property is initialized by the value of [`CMAKE_JOB_POOL_COMPILE`](../variable/cmake_job_pool_compile#variable:CMAKE_JOB_POOL_COMPILE "CMAKE_JOB_POOL_COMPILE").
cmake IMPORT_SUFFIX IMPORT\_SUFFIX
==============
What comes after the import library name.
Similar to the target property SUFFIX, but used for import libraries (typically corresponding to a DLL) instead of regular libraries. A target property that can be set to override the suffix (such as “.lib”) on an import library name.
cmake <LANG>_COMPILER_LAUNCHER <LANG>\_COMPILER\_LAUNCHER
==========================
This property is implemented only when `<LANG>` is `C` or `CXX`.
Specify a [;-list](../manual/cmake-language.7#cmake-language-lists) containing a command line for a compiler launching tool. The [Makefile Generators](../manual/cmake-generators.7#makefile-generators) and the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator will run this tool and pass the compiler and its arguments to the tool. Some example tools are distcc and ccache.
This property is initialized by the value of the [`CMAKE_<LANG>_COMPILER_LAUNCHER`](# "CMAKE_<LANG>_COMPILER_LAUNCHER") variable if it is set when a target is created.
| programming_docs |
cmake SKIP_BUILD_RPATH SKIP\_BUILD\_RPATH
==================
Should rpaths be used for the build tree.
SKIP\_BUILD\_RPATH is a boolean specifying whether to skip automatic generation of an rpath allowing the target to run from the build tree. This property is initialized by the value of the variable CMAKE\_SKIP\_BUILD\_RPATH if it is set when a target is created.
cmake INTERFACE_SOURCES INTERFACE\_SOURCES
==================
List of interface sources to compile into consuming targets.
Targets may populate this property to publish the sources for consuming targets to compile. The [`target_sources()`](../command/target_sources#command:target_sources "target_sources") command populates this property with values given to the `PUBLIC` and `INTERFACE` keywords. Projects may also get and set the property directly.
When target dependencies are specified using [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries"), CMake will read this property from all target dependencies to determine the sources of the consumer.
Contents of `INTERFACE_SOURCES` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake SOURCE_DIR SOURCE\_DIR
===========
This read-only property reports the value of the [`CMAKE_CURRENT_SOURCE_DIR`](../variable/cmake_current_source_dir#variable:CMAKE_CURRENT_SOURCE_DIR "CMAKE_CURRENT_SOURCE_DIR") variable in the directory in which the target was defined.
cmake RUNTIME_OUTPUT_DIRECTORY RUNTIME\_OUTPUT\_DIRECTORY
==========================
Output directory in which to build [RUNTIME](../manual/cmake-buildsystem.7#runtime-output-artifacts) target files.
This property specifies the directory into which runtime target files should be built. The property value may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)"). Multi-configuration generators (VS, Xcode) append a per-configuration subdirectory to the specified directory unless a generator expression is used.
This property is initialized by the value of the variable CMAKE\_RUNTIME\_OUTPUT\_DIRECTORY if it is set when a target is created.
See also the [`RUNTIME_OUTPUT_DIRECTORY_<CONFIG>`](# "RUNTIME_OUTPUT_DIRECTORY_<CONFIG>") target property.
cmake CUDA_PTX_COMPILATION CUDA\_PTX\_COMPILATION
======================
Compile CUDA sources to `.ptx` files instead of `.obj` files within [Object Libraries](../manual/cmake-buildsystem.7#object-libraries).
For example:
```
add_library(myptx OBJECT a.cu b.cu)
set_property(TARGET myptx PROPERTY CUDA_PTX_COMPILATION ON)
```
cmake AUTOUIC_OPTIONS AUTOUIC\_OPTIONS
================
Additional options for `uic` when using [`AUTOUIC`](autouic#prop_tgt:AUTOUIC "AUTOUIC")
This property holds additional command line options which will be used when `uic` is executed during the build via [`AUTOUIC`](autouic#prop_tgt:AUTOUIC "AUTOUIC"), i.e. it is equivalent to the optional `OPTIONS` argument of the [`qt4_wrap_ui()`](../module/findqt4#module:FindQt4 "FindQt4") macro.
By default it is empty.
This property is initialized by the value of the [`CMAKE_AUTOUIC_OPTIONS`](../variable/cmake_autouic_options#variable:CMAKE_AUTOUIC_OPTIONS "CMAKE_AUTOUIC_OPTIONS") variable if it is set when a target is created.
The options set on the target may be overridden by [`AUTOUIC_OPTIONS`](../prop_sf/autouic_options#prop_sf:AUTOUIC_OPTIONS "AUTOUIC_OPTIONS") set on the `.ui` source file.
This property may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions.
See the [`cmake-qt(7)`](../manual/cmake-qt.7#manual:cmake-qt(7) "cmake-qt(7)") manual for more information on using CMake with Qt.
cmake VS_DEBUGGER_WORKING_DIRECTORY VS\_DEBUGGER\_WORKING\_DIRECTORY
================================
Sets the local debugger working directory for Visual Studio C++ targets. This is defined in `<LocalDebuggerWorkingDirectory>` in the Visual Studio project file.
cmake OUTPUT_NAME OUTPUT\_NAME
============
Output name for target files.
This sets the base name for output files created for an executable or library target. If not set, the logical target name is used by default.
Contents of `OUTPUT_NAME` and the variants listed below may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)").
See also the variants:
* [`OUTPUT_NAME_<CONFIG>`](# "OUTPUT_NAME_<CONFIG>")
* [`ARCHIVE_OUTPUT_NAME_<CONFIG>`](# "ARCHIVE_OUTPUT_NAME_<CONFIG>")
* [`ARCHIVE_OUTPUT_NAME`](archive_output_name#prop_tgt:ARCHIVE_OUTPUT_NAME "ARCHIVE_OUTPUT_NAME")
* [`LIBRARY_OUTPUT_NAME_<CONFIG>`](# "LIBRARY_OUTPUT_NAME_<CONFIG>")
* [`LIBRARY_OUTPUT_NAME`](library_output_name#prop_tgt:LIBRARY_OUTPUT_NAME "LIBRARY_OUTPUT_NAME")
* [`RUNTIME_OUTPUT_NAME_<CONFIG>`](# "RUNTIME_OUTPUT_NAME_<CONFIG>")
* [`RUNTIME_OUTPUT_NAME`](runtime_output_name#prop_tgt:RUNTIME_OUTPUT_NAME "RUNTIME_OUTPUT_NAME")
cmake LINK_WHAT_YOU_USE LINK\_WHAT\_YOU\_USE
====================
This is a boolean option that when set to `TRUE` will automatically run `ldd -r -u` on the target after it is linked. In addition, the linker flag `-Wl,--no-as-needed` will be passed to the target with the link command so that all libraries specified on the command line will be linked into the target. This will result in the link producing a list of libraries that provide no symbols used by this target but are being linked to it. This is only applicable to executable and shared library targets and will only work when ld and ldd accept the flags used.
This property is initialized by the value of the [`CMAKE_LINK_WHAT_YOU_USE`](../variable/cmake_link_what_you_use#variable:CMAKE_LINK_WHAT_YOU_USE "CMAKE_LINK_WHAT_YOU_USE") variable if it is set when a target is created.
cmake ALIASED_TARGET ALIASED\_TARGET
===============
Name of target aliased by this target.
If this is an [Alias Target](../manual/cmake-buildsystem.7#alias-targets), this property contains the name of the target aliased.
cmake LINK_FLAGS LINK\_FLAGS
===========
Additional flags to use when linking this target.
The LINK\_FLAGS property can be used to add extra flags to the link step of a target. LINK\_FLAGS\_<CONFIG> will add to the configuration <CONFIG>, for example, DEBUG, RELEASE, MINSIZEREL, RELWITHDEBINFO.
cmake INTERFACE_POSITION_INDEPENDENT_CODE INTERFACE\_POSITION\_INDEPENDENT\_CODE
======================================
Whether consumers need to create a position-independent target
The `INTERFACE_POSITION_INDEPENDENT_CODE` property informs consumers of this target whether they must set their [`POSITION_INDEPENDENT_CODE`](position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE") property to `ON`. If this property is set to `ON`, then the [`POSITION_INDEPENDENT_CODE`](position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE") property on all consumers will be set to `ON`. Similarly, if this property is set to `OFF`, then the [`POSITION_INDEPENDENT_CODE`](position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE") property on all consumers will be set to `OFF`. If this property is undefined, then consumers will determine their [`POSITION_INDEPENDENT_CODE`](position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE") property by other means. Consumers must ensure that the targets that they link to have a consistent requirement for their `INTERFACE_POSITION_INDEPENDENT_CODE` property.
cmake RESOURCE RESOURCE
========
Specify resource files in a [`FRAMEWORK`](framework#prop_tgt:FRAMEWORK "FRAMEWORK") or [`BUNDLE`](bundle#prop_tgt:BUNDLE "BUNDLE").
Target marked with the [`FRAMEWORK`](framework#prop_tgt:FRAMEWORK "FRAMEWORK") or [`BUNDLE`](bundle#prop_tgt:BUNDLE "BUNDLE") property generate framework or application bundle (both OS X and iOS is supported) or normal shared libraries on other platforms. This property may be set to a list of files to be placed in the corresponding directory (eg. `Resources` directory for OS X) inside the bundle. On non-Apple platforms these files may be installed using the `RESOURCE` option to the `install(TARGETS)` command.
Following example of Application Bundle:
```
add_executable(ExecutableTarget
addDemo.c
resourcefile.txt
appresourcedir/appres.txt
)
target_link_libraries(ExecutableTarget heymath mul)
set(RESOURCE_FILES
resourcefile.txt
appresourcedir/appres.txt
)
set_target_properties(ExecutableTarget PROPERTIES
MACOSX_BUNDLE TRUE
MACOSX_FRAMEWORK_IDENTIFIER org.cmake.ExecutableTarget
RESOURCE "${RESOURCE_FILES}"
)
```
will produce flat structure for iOS systems:
```
ExecutableTarget.app
appres.txt
ExecutableTarget
Info.plist
resourcefile.txt
```
For OS X systems it will produce following directory structure:
```
ExecutableTarget.app/
Contents
Info.plist
MacOS
ExecutableTarget
Resources
appres.txt
resourcefile.txt
```
For Linux, such cmake script produce following files:
```
ExecutableTarget
Resources
appres.txt
resourcefile.txt
```
cmake INTERFACE_AUTOUIC_OPTIONS INTERFACE\_AUTOUIC\_OPTIONS
===========================
List of interface options to pass to uic.
Targets may populate this property to publish the options required to use when invoking `uic`. Consuming targets can add entries to their own [`AUTOUIC_OPTIONS`](autouic_options#prop_tgt:AUTOUIC_OPTIONS "AUTOUIC_OPTIONS") property such as `$<TARGET_PROPERTY:foo,INTERFACE_AUTOUIC_OPTIONS>` to use the uic options specified in the interface of `foo`. This is done automatically by the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command.
This property supports generator expressions. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions.
cmake COMPATIBLE_INTERFACE_STRING COMPATIBLE\_INTERFACE\_STRING
=============================
Properties which must be string-compatible with their link interface
The `COMPATIBLE_INTERFACE_STRING` property may contain a list of properties for this target which must be the same when evaluated as a string in the `INTERFACE` variant of the property all linked dependees. For example, if a property `FOO` appears in the list, then for each dependee, the `INTERFACE_FOO` property content in all of its dependencies must be equal with each other, and with the `FOO` property in the depender. If the property is not set, then it is ignored.
Note that for each dependee, the set of properties specified in this property must not intersect with the set specified in any of the other [Compatible Interface Properties](../manual/cmake-buildsystem.7#compatible-interface-properties).
cmake <CONFIG>_OUTPUT_NAME <CONFIG>\_OUTPUT\_NAME
======================
Old per-configuration target file base name. Use [`OUTPUT_NAME_<CONFIG>`](# "OUTPUT_NAME_<CONFIG>") instead.
This is a configuration-specific version of the [`OUTPUT_NAME`](output_name#prop_tgt:OUTPUT_NAME "OUTPUT_NAME") target property.
cmake IMPORTED_NO_SONAME_<CONFIG> IMPORTED\_NO\_SONAME\_<CONFIG>
==============================
<CONFIG>-specific version of IMPORTED\_NO\_SONAME property.
Configuration names correspond to those provided by the project from which the target is imported.
cmake IMPORTED_LINK_INTERFACE_MULTIPLICITY IMPORTED\_LINK\_INTERFACE\_MULTIPLICITY
=======================================
Repetition count for cycles of IMPORTED static libraries.
This is LINK\_INTERFACE\_MULTIPLICITY for IMPORTED targets.
cmake WIN32_EXECUTABLE WIN32\_EXECUTABLE
=================
Build an executable with a WinMain entry point on windows.
When this property is set to true the executable when linked on Windows will be created with a WinMain() entry point instead of just main(). This makes it a GUI executable instead of a console application. See the CMAKE\_MFC\_FLAG variable documentation to configure use of MFC for WinMain executables. This property is initialized by the value of the variable CMAKE\_WIN32\_EXECUTABLE if it is set when a target is created.
cmake CUDA_STANDARD CUDA\_STANDARD
==============
The CUDA/C++ standard whose features are requested to build this target.
This property specifies the CUDA/C++ standard whose features are requested to build this target. For some compilers, this results in adding a flag such as `-std=gnu++11` to the compile line.
Supported values are `98`, `11`.
If the value requested does not result in a compile flag being added for the compiler in use, a previous standard flag will be added instead. This means that using:
```
set_property(TARGET tgt PROPERTY CUDA_STANDARD 11)
```
with a compiler which does not support `-std=gnu++11` or an equivalent flag will not result in an error or warning, but will instead add the `-std=gnu++98` flag if supported. This “decay” behavior may be controlled with the [`CUDA_STANDARD_REQUIRED`](cuda_standard_required#prop_tgt:CUDA_STANDARD_REQUIRED "CUDA_STANDARD_REQUIRED") target property. Additionally, the [`CUDA_EXTENSIONS`](cuda_extensions#prop_tgt:CUDA_EXTENSIONS "CUDA_EXTENSIONS") target property may be used to control whether compiler-specific extensions are enabled on a per-target basis.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
This property is initialized by the value of the [`CMAKE_CUDA_STANDARD`](../variable/cmake_cuda_standard#variable:CMAKE_CUDA_STANDARD "CMAKE_CUDA_STANDARD") variable if it is set when a target is created.
cmake AUTOUIC_SEARCH_PATHS AUTOUIC\_SEARCH\_PATHS
======================
Search path list used by [`AUTOUIC`](autouic#prop_tgt:AUTOUIC "AUTOUIC") to find included `.ui` files.
This property is initialized by the value of the [`CMAKE_AUTOUIC_SEARCH_PATHS`](../variable/cmake_autouic_search_paths#variable:CMAKE_AUTOUIC_SEARCH_PATHS "CMAKE_AUTOUIC_SEARCH_PATHS") variable if it is set when a target is created. Otherwise it is empty.
See the [`cmake-qt(7)`](../manual/cmake-qt.7#manual:cmake-qt(7) "cmake-qt(7)") manual for more information on using CMake with Qt.
cmake VS_GLOBAL_PROJECT_TYPES VS\_GLOBAL\_PROJECT\_TYPES
==========================
Visual Studio project type(s).
Can be set to one or more UUIDs recognized by Visual Studio to indicate the type of project. This value is copied verbatim into the generated project file. Example for a managed C++ unit testing project:
```
{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}
```
UUIDs are semicolon-delimited.
cmake IMPORTED_LOCATION_<CONFIG> IMPORTED\_LOCATION\_<CONFIG>
============================
<CONFIG>-specific version of IMPORTED\_LOCATION property.
Configuration names correspond to those provided by the project from which the target is imported.
cmake IMPORTED_SONAME IMPORTED\_SONAME
================
The “soname” of an IMPORTED target of shared library type.
Set this to the “soname” embedded in an imported shared library. This is meaningful only on platforms supporting the feature. Ignored for non-imported targets.
cmake IMPORTED_LINK_INTERFACE_LANGUAGES_<CONFIG> IMPORTED\_LINK\_INTERFACE\_LANGUAGES\_<CONFIG>
==============================================
<CONFIG>-specific version of IMPORTED\_LINK\_INTERFACE\_LANGUAGES.
Configuration names correspond to those provided by the project from which the target is imported. If set, this property completely overrides the generic property for the named configuration.
cmake IMPORTED_OBJECTS_<CONFIG> IMPORTED\_OBJECTS\_<CONFIG>
===========================
<CONFIG>-specific version of [`IMPORTED_OBJECTS`](imported_objects#prop_tgt:IMPORTED_OBJECTS "IMPORTED_OBJECTS") property.
Configuration names correspond to those provided by the project from which the target is imported.
cmake RULE_LAUNCH_COMPILE RULE\_LAUNCH\_COMPILE
=====================
Specify a launcher for compile rules.
See the global property of the same name for details. This overrides the global and directory property for a target.
cmake VS_USER_PROPS VS\_USER\_PROPS
===============
Sets the user props file to be included in the visual studio C++ project file. The standard path is `$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props`, which is in most cases the same as `%LOCALAPPDATA%\\Microsoft\\MSBuild\\v4.0\\Microsoft.Cpp.Win32.user.props` or `%LOCALAPPDATA%\\Microsoft\\MSBuild\\v4.0\\Microsoft.Cpp.x64.user.props`.
The `*.user.props` files can be used for Visual Studio wide configuration which is independent from cmake.
cmake VS_WINRT_REFERENCES VS\_WINRT\_REFERENCES
=====================
Visual Studio project Windows Runtime Metadata references
Adds one or more semicolon-delimited WinRT references to a generated Visual Studio project. For example, “Windows;Windows.UI.Core”.
cmake CUDA_STANDARD_REQUIRED CUDA\_STANDARD\_REQUIRED
========================
Boolean describing whether the value of [`CUDA_STANDARD`](cuda_standard#prop_tgt:CUDA_STANDARD "CUDA_STANDARD") is a requirement.
If this property is set to `ON`, then the value of the [`CUDA_STANDARD`](cuda_standard#prop_tgt:CUDA_STANDARD "CUDA_STANDARD") target property is treated as a requirement. If this property is `OFF` or unset, the [`CUDA_STANDARD`](cuda_standard#prop_tgt:CUDA_STANDARD "CUDA_STANDARD") target property is treated as optional and may “decay” to a previous standard if the requested is not available. For compilers that have no notion of a standard level, such as MSVC, this has no effect.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
This property is initialized by the value of the [`CMAKE_CUDA_STANDARD_REQUIRED`](../variable/cmake_cuda_standard_required#variable:CMAKE_CUDA_STANDARD_REQUIRED "CMAKE_CUDA_STANDARD_REQUIRED") variable if it is set when a target is created.
cmake LIBRARY_OUTPUT_DIRECTORY_<CONFIG> LIBRARY\_OUTPUT\_DIRECTORY\_<CONFIG>
====================================
Per-configuration output directory for [LIBRARY](../manual/cmake-buildsystem.7#library-output-artifacts) target files.
This is a per-configuration version of the [`LIBRARY_OUTPUT_DIRECTORY`](library_output_directory#prop_tgt:LIBRARY_OUTPUT_DIRECTORY "LIBRARY_OUTPUT_DIRECTORY") target property, but multi-configuration generators (VS, Xcode) do NOT append a per-configuration subdirectory to the specified directory. This property is initialized by the value of the [`CMAKE_LIBRARY_OUTPUT_DIRECTORY_<CONFIG>`](# "CMAKE_LIBRARY_OUTPUT_DIRECTORY_<CONFIG>") variable if it is set when a target is created.
Contents of `LIBRARY_OUTPUT_DIRECTORY_<CONFIG>` may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)").
cmake VS_SCC_AUXPATH VS\_SCC\_AUXPATH
================
Visual Studio Source Code Control Aux Path.
Can be set to change the visual studio source code control auxpath property.
cmake <LANG>_INCLUDE_WHAT_YOU_USE <LANG>\_INCLUDE\_WHAT\_YOU\_USE
===============================
This property is implemented only when `<LANG>` is `C` or `CXX`.
Specify a [;-list](../manual/cmake-language.7#cmake-language-lists) containing a command line for the `include-what-you-use` tool. The [Makefile Generators](../manual/cmake-generators.7#makefile-generators) and the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator will run this tool along with the compiler and report a warning if the tool reports any problems.
This property is initialized by the value of the [`CMAKE_<LANG>_INCLUDE_WHAT_YOU_USE`](# "CMAKE_<LANG>_INCLUDE_WHAT_YOU_USE") variable if it is set when a target is created.
| programming_docs |
cmake ANDROID_JAR_DIRECTORIES ANDROID\_JAR\_DIRECTORIES
=========================
Set the Android property that specifies directories to search for the JAR libraries.
This a string property that contains the directory paths separated by semicolons. This property is initialized by the value of the [`CMAKE_ANDROID_JAR_DIRECTORIES`](../variable/cmake_android_jar_directories#variable:CMAKE_ANDROID_JAR_DIRECTORIES "CMAKE_ANDROID_JAR_DIRECTORIES") variable if it is set when a target is created.
Contents of `ANDROID_JAR_DIRECTORIES` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions.
cmake IMPORTED_OBJECTS IMPORTED\_OBJECTS
=================
[;-list](../manual/cmake-language.7#cmake-language-lists) of absolute paths to the object files on disk for an [imported](../manual/cmake-buildsystem.7#imported-targets) [object library](../manual/cmake-buildsystem.7#object-libraries).
Ignored for non-imported targets.
Projects may skip `IMPORTED_OBJECTS` if the configuration-specific property [`IMPORTED_OBJECTS_<CONFIG>`](# "IMPORTED_OBJECTS_<CONFIG>") is set instead.
cmake BUILD_RPATH BUILD\_RPATH
============
A [;-list](../manual/cmake-language.7#cmake-language-lists) specifying runtime path (`RPATH`) entries to add to binaries linked in the build tree (for platforms that support it). The entries will *not* be used for binaries in the install tree. See also the [`INSTALL_RPATH`](install_rpath#prop_tgt:INSTALL_RPATH "INSTALL_RPATH") target property.
This property is initialized by the value of the variable [`CMAKE_BUILD_RPATH`](../variable/cmake_build_rpath#variable:CMAKE_BUILD_RPATH "CMAKE_BUILD_RPATH") if it is set when a target is created.
cmake IMPORTED_LINK_INTERFACE_LIBRARIES_<CONFIG> IMPORTED\_LINK\_INTERFACE\_LIBRARIES\_<CONFIG>
==============================================
<CONFIG>-specific version of IMPORTED\_LINK\_INTERFACE\_LIBRARIES.
Configuration names correspond to those provided by the project from which the target is imported. If set, this property completely overrides the generic property for the named configuration.
This property is ignored if the target also has a non-empty INTERFACE\_LINK\_LIBRARIES property.
This property is deprecated. Use INTERFACE\_LINK\_LIBRARIES instead.
cmake ANDROID_ANT_ADDITIONAL_OPTIONS ANDROID\_ANT\_ADDITIONAL\_OPTIONS
=================================
Set the additional options for Android Ant build system. This is a string value containing all command line options for the Ant build. This property is initialized by the value of the [`CMAKE_ANDROID_ANT_ADDITIONAL_OPTIONS`](../variable/cmake_android_ant_additional_options#variable:CMAKE_ANDROID_ANT_ADDITIONAL_OPTIONS "CMAKE_ANDROID_ANT_ADDITIONAL_OPTIONS") variable if it is set when a target is created.
cmake VS_CONFIGURATION_TYPE VS\_CONFIGURATION\_TYPE
=======================
Visual Studio project configuration type.
Sets the `ConfigurationType` attribute for a generated Visual Studio project. If this property is set, it overrides the default setting that is based on the target type (e.g. `StaticLibrary`, `Application`, …).
Supported on [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators) for VS 2010 and higher.
cmake LINK_SEARCH_END_STATIC LINK\_SEARCH\_END\_STATIC
=========================
End a link line such that static system libraries are used.
Some linkers support switches such as -Bstatic and -Bdynamic to determine whether to use static or shared libraries for -lXXX options. CMake uses these options to set the link type for libraries whose full paths are not known or (in some cases) are in implicit link directories for the platform. By default CMake adds an option at the end of the library list (if necessary) to set the linker search type back to its starting type. This property switches the final linker search type to -Bstatic regardless of how it started.
This property is initialized by the value of the variable CMAKE\_LINK\_SEARCH\_END\_STATIC if it is set when a target is created.
See also LINK\_SEARCH\_START\_STATIC.
cmake ANDROID_SKIP_ANT_STEP ANDROID\_SKIP\_ANT\_STEP
========================
Set the Android property that defines whether or not to skip the Ant build step. This is a boolean property initialized by the value of the [`CMAKE_ANDROID_SKIP_ANT_STEP`](../variable/cmake_android_skip_ant_step#variable:CMAKE_ANDROID_SKIP_ANT_STEP "CMAKE_ANDROID_SKIP_ANT_STEP") variable if it is set when a target is created.
cmake STATIC_LIBRARY_FLAGS_<CONFIG> STATIC\_LIBRARY\_FLAGS\_<CONFIG>
================================
Per-configuration flags for creating a static library.
This is the configuration-specific version of STATIC\_LIBRARY\_FLAGS.
cmake COMPATIBLE_INTERFACE_NUMBER_MIN COMPATIBLE\_INTERFACE\_NUMBER\_MIN
==================================
Properties whose maximum value from the link interface will be used.
The `COMPATIBLE_INTERFACE_NUMBER_MIN` property may contain a list of properties for this target whose minimum value may be read at generate time when evaluated in the `INTERFACE` variant of the property of all linked dependees. For example, if a property `FOO` appears in the list, then for each dependee, the `INTERFACE_FOO` property content in all of its dependencies will be compared with each other and with the `FOO` property in the depender. When reading the `FOO` property at generate time, the minimum value will be returned. If the property is not set, then it is ignored.
Note that for each dependee, the set of properties specified in this property must not intersect with the set specified in any of the other [Compatible Interface Properties](../manual/cmake-buildsystem.7#compatible-interface-properties).
cmake MACOSX_BUNDLE MACOSX\_BUNDLE
==============
Build an executable as an Application Bundle on OS X or iOS.
When this property is set to `TRUE` the executable when built on OS X or iOS will be created as an application bundle. This makes it a GUI executable that can be launched from the Finder. See the [`MACOSX_FRAMEWORK_INFO_PLIST`](macosx_framework_info_plist#prop_tgt:MACOSX_FRAMEWORK_INFO_PLIST "MACOSX_FRAMEWORK_INFO_PLIST") target property for information about creation of the `Info.plist` file for the application bundle. This property is initialized by the value of the variable [`CMAKE_MACOSX_BUNDLE`](../variable/cmake_macosx_bundle#variable:CMAKE_MACOSX_BUNDLE "CMAKE_MACOSX_BUNDLE") if it is set when a target is created.
cmake IMPORTED_NO_SONAME IMPORTED\_NO\_SONAME
====================
Specifies that an IMPORTED shared library target has no “soname”.
Set this property to true for an imported shared library file that has no “soname” field. CMake may adjust generated link commands for some platforms to prevent the linker from using the path to the library in place of its missing soname. Ignored for non-imported targets.
cmake IMPORTED_LOCATION IMPORTED\_LOCATION
==================
Full path to the main file on disk for an IMPORTED target.
Set this to the location of an IMPORTED target file on disk. For executables this is the location of the executable file. For bundles on OS X this is the location of the executable file inside Contents/MacOS under the application bundle folder. For static libraries and modules this is the location of the library or module. For shared libraries on non-DLL platforms this is the location of the shared library. For frameworks on OS X this is the location of the library file symlink just inside the framework folder. For DLLs this is the location of the “.dll” part of the library. For UNKNOWN libraries this is the location of the file to be linked. Ignored for non-imported targets.
Projects may skip IMPORTED\_LOCATION if the configuration-specific property IMPORTED\_LOCATION\_<CONFIG> is set. To get the location of an imported target read one of the LOCATION or LOCATION\_<CONFIG> properties.
cmake AUTOMOC_DEPEND_FILTERS AUTOMOC\_DEPEND\_FILTERS
========================
Filter definitions used by [`AUTOMOC`](automoc#prop_tgt:AUTOMOC "AUTOMOC") to extract file names from source code as additional dependencies for the `moc` file.
This property is only used if the [`AUTOMOC`](automoc#prop_tgt:AUTOMOC "AUTOMOC") property is `ON` for this target.
Filters are defined as `KEYWORD;REGULAR_EXPRESSION` pairs. First the file content is searched for `KEYWORD`. If it is found at least once, then file names are extracted by successively searching for `REGULAR_EXPRESSION` and taking the first match group.
Consider a filter extracts the file name `DEP` from the content of a file `FOO`. If `DEP` changes, then the `moc` file for `FOO` gets rebuilt. The file `DEP` is searched for first in the vicinity of `FOO` and afterwards in the target’s [`INCLUDE_DIRECTORIES`](include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES").
By default [`AUTOMOC_DEPEND_FILTERS`](#prop_tgt:AUTOMOC_DEPEND_FILTERS "AUTOMOC_DEPEND_FILTERS") is initialized from [`CMAKE_AUTOMOC_DEPEND_FILTERS`](../variable/cmake_automoc_depend_filters#variable:CMAKE_AUTOMOC_DEPEND_FILTERS "CMAKE_AUTOMOC_DEPEND_FILTERS"), which is empty by default.
See the [`cmake-qt(7)`](../manual/cmake-qt.7#manual:cmake-qt(7) "cmake-qt(7)") manual for more information on using CMake with Qt.
Example
=======
Consider a file `FOO.hpp` holds a custom macro `OBJ_JSON_FILE` and we want the `moc` file to depend on the macro`s file name argument:
```
class My_Class : public QObject
{
Q_OBJECT
OBJ_JSON_FILE ( "DEP.json" )
...
};
```
Then we might use [`CMAKE_AUTOMOC_DEPEND_FILTERS`](../variable/cmake_automoc_depend_filters#variable:CMAKE_AUTOMOC_DEPEND_FILTERS "CMAKE_AUTOMOC_DEPEND_FILTERS") to define a filter like this:
```
set(CMAKE_AUTOMOC_DEPEND_FILTERS
"OBJ_JSON_FILE" "[\n][ \t]*OBJ_JSON_FILE[ \t]*\\([ \t]*\"([^\"]+)\""
)
```
cmake INTERFACE_SYSTEM_INCLUDE_DIRECTORIES INTERFACE\_SYSTEM\_INCLUDE\_DIRECTORIES
=======================================
List of public system include directories for a library.
Targets may populate this property to publish the include directories which contain system headers, and therefore should not result in compiler warnings. The [`target_include_directories(SYSTEM)`](../command/target_include_directories#command:target_include_directories "target_include_directories") command signature populates this property with values given to the `PUBLIC` and `INTERFACE` keywords.
Projects may also get and set the property directly, but must be aware that adding directories to this property does not make those directories used during compilation. Adding directories to this property marks directories as `SYSTEM` which otherwise would be used in a non-`SYSTEM` manner. This can appear similar to ‘duplication’, so prefer the high-level [`target_include_directories(SYSTEM)`](../command/target_include_directories#command:target_include_directories "target_include_directories") command and avoid setting the property by low-level means.
When target dependencies are specified using [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries"), CMake will read this property from all target dependencies to mark the same include directories as containing system headers.
Contents of `INTERFACE_SYSTEM_INCLUDE_DIRECTORIES` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake IMPORTED_LIBNAME_<CONFIG> IMPORTED\_LIBNAME\_<CONFIG>
===========================
<CONFIG>-specific version of [`IMPORTED_LIBNAME`](imported_libname#prop_tgt:IMPORTED_LIBNAME "IMPORTED_LIBNAME") property.
Configuration names correspond to those provided by the project from which the target is imported.
cmake IMPORTED_IMPLIB_<CONFIG> IMPORTED\_IMPLIB\_<CONFIG>
==========================
<CONFIG>-specific version of IMPORTED\_IMPLIB property.
Configuration names correspond to those provided by the project from which the target is imported.
cmake MACOSX_FRAMEWORK_INFO_PLIST MACOSX\_FRAMEWORK\_INFO\_PLIST
==============================
Specify a custom `Info.plist` template for a OS X and iOS Framework.
A library target with [`FRAMEWORK`](framework#prop_tgt:FRAMEWORK "FRAMEWORK") enabled will be built as a framework on OS X. By default its `Info.plist` file is created by configuring a template called `MacOSXFrameworkInfo.plist.in` located in the [`CMAKE_MODULE_PATH`](../variable/cmake_module_path#variable:CMAKE_MODULE_PATH "CMAKE_MODULE_PATH"). This property specifies an alternative template file name which may be a full path.
The following target properties may be set to specify content to be configured into the file:
`MACOSX_FRAMEWORK_BUNDLE_VERSION` Sets `CFBundleVersion`.
`MACOSX_FRAMEWORK_ICON_FILE` Sets `CFBundleIconFile`.
`MACOSX_FRAMEWORK_IDENTIFIER` Sets `CFBundleIdentifier`.
`MACOSX_FRAMEWORK_SHORT_VERSION_STRING` Sets `CFBundleShortVersionString`. CMake variables of the same name may be set to affect all targets in a directory that do not have each specific property set. If a custom `Info.plist` is specified by this property it may of course hard-code all the settings instead of using the target properties.
cmake INSTALL_RPATH_USE_LINK_PATH INSTALL\_RPATH\_USE\_LINK\_PATH
===============================
Add paths to linker search and installed rpath.
INSTALL\_RPATH\_USE\_LINK\_PATH is a boolean that if set to true will append directories in the linker search path and outside the project to the INSTALL\_RPATH. This property is initialized by the value of the variable CMAKE\_INSTALL\_RPATH\_USE\_LINK\_PATH if it is set when a target is created.
cmake VS_GLOBAL_<variable> VS\_GLOBAL\_<variable>
======================
Visual Studio project-specific global variable.
Tell the Visual Studio generator to set the global variable ‘<variable>’ to a given value in the generated Visual Studio project. Ignored on other generators. Qt integration works better if VS\_GLOBAL\_QtVersion is set to the version FindQt4.cmake found. For example, “4.7.3”
cmake LINK_INTERFACE_MULTIPLICITY LINK\_INTERFACE\_MULTIPLICITY
=============================
Repetition count for STATIC libraries with cyclic dependencies.
When linking to a STATIC library target with cyclic dependencies the linker may need to scan more than once through the archives in the strongly connected component of the dependency graph. CMake by default constructs the link line so that the linker will scan through the component at least twice. This property specifies the minimum number of scans if it is larger than the default. CMake uses the largest value specified by any target in a component.
cmake PDB_NAME PDB\_NAME
=========
Output name for the MS debug symbol `.pdb` file generated by the linker for an executable or shared library target.
This property specifies the base name for the debug symbols file. If not set, the [`OUTPUT_NAME`](output_name#prop_tgt:OUTPUT_NAME "OUTPUT_NAME") target property value or logical target name is used by default.
Note
This property does not apply to STATIC library targets because no linker is invoked to produce them so they have no linker-generated `.pdb` file containing debug symbols.
The linker-generated program database files are specified by the `/pdb` linker flag and are not the same as compiler-generated program database files specified by the `/Fd` compiler flag. Use the [`COMPILE_PDB_NAME`](compile_pdb_name#prop_tgt:COMPILE_PDB_NAME "COMPILE_PDB_NAME") property to specify the latter.
cmake BUNDLE BUNDLE
======
This target is a `CFBundle` on the OS X.
If a module library target has this property set to true it will be built as a `CFBundle` when built on the mac. It will have the directory structure required for a `CFBundle` and will be suitable to be used for creating Browser Plugins or other application resources.
cmake VS_KEYWORD VS\_KEYWORD
===========
Visual Studio project keyword for VS 9 (2008) and older.
Can be set to change the visual studio keyword, for example Qt integration works better if this is set to Qt4VSv1.0.
Use the [`VS_GLOBAL_KEYWORD`](vs_global_keyword#prop_tgt:VS_GLOBAL_KEYWORD "VS_GLOBAL_KEYWORD") target property to set the keyword for Visual Studio 10 (2010) and newer.
cmake FRAMEWORK FRAMEWORK
=========
Build `SHARED` or `STATIC` library as Framework Bundle on the OS X and iOS.
If such a library target has this property set to `TRUE` it will be built as a framework when built on the OS X and iOS. It will have the directory structure required for a framework and will be suitable to be used with the `-framework` option
To customize `Info.plist` file in the framework, use [`MACOSX_FRAMEWORK_INFO_PLIST`](macosx_framework_info_plist#prop_tgt:MACOSX_FRAMEWORK_INFO_PLIST "MACOSX_FRAMEWORK_INFO_PLIST") target property.
For OS X see also the [`FRAMEWORK_VERSION`](framework_version#prop_tgt:FRAMEWORK_VERSION "FRAMEWORK_VERSION") target property.
Example of creation `dynamicFramework`:
```
add_library(dynamicFramework SHARED
dynamicFramework.c
dynamicFramework.h
)
set_target_properties(dynamicFramework PROPERTIES
FRAMEWORK TRUE
FRAMEWORK_VERSION C
MACOSX_FRAMEWORK_IDENTIFIER com.cmake.dynamicFramework
MACOSX_FRAMEWORK_INFO_PLIST Info.plist
# "current version" in semantic format in Mach-O binary file
VERSION 16.4.0
# "compatibility version" in semantic format in Mach-O binary file
SOVERSION 1.0.0
PUBLIC_HEADER dynamicFramework.h
XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "iPhone Developer"
)
```
cmake MAP_IMPORTED_CONFIG_<CONFIG> MAP\_IMPORTED\_CONFIG\_<CONFIG>
===============================
Map from project configuration to [imported target](../manual/cmake-buildsystem.7#imported-targets)’s configuration.
Set this to the list of configurations of an imported target that may be used for the current project’s `<CONFIG>` configuration. Targets imported from another project may not provide the same set of configuration names available in the current project. Setting this property tells CMake what imported configurations are suitable for use when building the `<CONFIG>` configuration. The first configuration in the list found to be provided by the imported target (i.e. via [`IMPORTED_LOCATION_<CONFIG>`](# "IMPORTED_LOCATION_<CONFIG>") for the mapped-to `<CONFIG>`) is selected. As a special case, an empty list element refers to the configuration-less imported target location (i.e. [`IMPORTED_LOCATION`](imported_location#prop_tgt:IMPORTED_LOCATION "IMPORTED_LOCATION")).
If this property is set and no matching configurations are available, then the imported target is considered to be not found. This property is ignored for non-imported targets.
This property is initialized by the value of the [`CMAKE_MAP_IMPORTED_CONFIG_<CONFIG>`](# "CMAKE_MAP_IMPORTED_CONFIG_<CONFIG>") variable if it is set when a target is created.
Example
-------
For example creating imported C++ library `foo`:
```
add_library(foo STATIC IMPORTED)
```
Use `foo_debug` path for `Debug` build type:
```
set_property(
TARGET foo APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG
)
set_target_properties(foo PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
IMPORTED_LOCATION_DEBUG "${foo_debug}"
)
```
Use `foo_release` path for `Release` build type:
```
set_property(
TARGET foo APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE
)
set_target_properties(foo PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "CXX"
IMPORTED_LOCATION_RELEASE "${foo_release}"
)
```
Use `Release` version of library for `MinSizeRel` and `RelWithDebInfo` build types:
```
set_target_properties(foo PROPERTIES
MAP_IMPORTED_CONFIG_MINSIZEREL Release
MAP_IMPORTED_CONFIG_RELWITHDEBINFO Release
)
```
| programming_docs |
cmake AUTORCC AUTORCC
=======
Should the target be processed with autorcc (for Qt projects).
`AUTORCC` is a boolean specifying whether CMake will handle the Qt `rcc` code generator automatically, i.e. without having to use the [`QT4_ADD_RESOURCES()`](../module/findqt4#module:FindQt4 "FindQt4") or `QT5_ADD_RESOURCES()` macro. Currently Qt4 and Qt5 are supported.
When this property is `ON`, CMake will handle `.qrc` files added as target sources at build time and invoke `rcc` accordingly. This property is initialized by the value of the [`CMAKE_AUTORCC`](../variable/cmake_autorcc#variable:CMAKE_AUTORCC "CMAKE_AUTORCC") variable if it is set when a target is created.
Additional command line options for rcc can be set via the [`AUTORCC_OPTIONS`](../prop_sf/autorcc_options#prop_sf:AUTORCC_OPTIONS "AUTORCC_OPTIONS") source file property on the `.qrc` file.
The global property [`AUTOGEN_TARGETS_FOLDER`](../prop_gbl/autogen_targets_folder#prop_gbl:AUTOGEN_TARGETS_FOLDER "AUTOGEN_TARGETS_FOLDER") can be used to group the autorcc targets together in an IDE, e.g. in MSVS.
The global property [`AUTOGEN_SOURCE_GROUP`](../prop_gbl/autogen_source_group#prop_gbl:AUTOGEN_SOURCE_GROUP "AUTOGEN_SOURCE_GROUP") can be used to group files generated by [`AUTORCC`](#prop_tgt:AUTORCC "AUTORCC") together in an IDE, e.g. in MSVS.
When there are multiple `.qrc` files with the same name, CMake will generate unspecified unique names for `rcc`. Therefore if `Q_INIT_RESOURCE()` or `Q_CLEANUP_RESOURCE()` need to be used the `.qrc` file name must be unique.
Source files can be excluded from [`AUTORCC`](#prop_tgt:AUTORCC "AUTORCC") processing by enabling [`SKIP_AUTORCC`](../prop_sf/skip_autorcc#prop_sf:SKIP_AUTORCC "SKIP_AUTORCC") or the broader [`SKIP_AUTOGEN`](../prop_sf/skip_autogen#prop_sf:SKIP_AUTOGEN "SKIP_AUTOGEN").
See the [`cmake-qt(7)`](../manual/cmake-qt.7#manual:cmake-qt(7) "cmake-qt(7)") manual for more information on using CMake with Qt.
cmake LIBRARY_OUTPUT_NAME LIBRARY\_OUTPUT\_NAME
=====================
Output name for [LIBRARY](../manual/cmake-buildsystem.7#library-output-artifacts) target files.
This property specifies the base name for library target files. It overrides [`OUTPUT_NAME`](output_name#prop_tgt:OUTPUT_NAME "OUTPUT_NAME") and [`OUTPUT_NAME_<CONFIG>`](# "OUTPUT_NAME_<CONFIG>") properties.
See also the [`LIBRARY_OUTPUT_NAME_<CONFIG>`](# "LIBRARY_OUTPUT_NAME_<CONFIG>") target property.
cmake PUBLIC_HEADER PUBLIC\_HEADER
==============
Specify public header files in a [`FRAMEWORK`](framework#prop_tgt:FRAMEWORK "FRAMEWORK") shared library target.
Shared library targets marked with the [`FRAMEWORK`](framework#prop_tgt:FRAMEWORK "FRAMEWORK") property generate frameworks on OS X, iOS and normal shared libraries on other platforms. This property may be set to a list of header files to be placed in the `Headers` directory inside the framework folder. On non-Apple platforms these headers may be installed using the `PUBLIC_HEADER` option to the `install(TARGETS)` command.
cmake RUNTIME_OUTPUT_NAME RUNTIME\_OUTPUT\_NAME
=====================
Output name for [RUNTIME](../manual/cmake-buildsystem.7#runtime-output-artifacts) target files.
This property specifies the base name for runtime target files. It overrides [`OUTPUT_NAME`](output_name#prop_tgt:OUTPUT_NAME "OUTPUT_NAME") and [`OUTPUT_NAME_<CONFIG>`](# "OUTPUT_NAME_<CONFIG>") properties.
See also the [`RUNTIME_OUTPUT_NAME_<CONFIG>`](# "RUNTIME_OUTPUT_NAME_<CONFIG>") target property.
cmake CXX_STANDARD_REQUIRED CXX\_STANDARD\_REQUIRED
=======================
Boolean describing whether the value of [`CXX_STANDARD`](cxx_standard#prop_tgt:CXX_STANDARD "CXX_STANDARD") is a requirement.
If this property is set to `ON`, then the value of the [`CXX_STANDARD`](cxx_standard#prop_tgt:CXX_STANDARD "CXX_STANDARD") target property is treated as a requirement. If this property is `OFF` or unset, the [`CXX_STANDARD`](cxx_standard#prop_tgt:CXX_STANDARD "CXX_STANDARD") target property is treated as optional and may “decay” to a previous standard if the requested is not available. For compilers that have no notion of a standard level, such as MSVC, this has no effect.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
This property is initialized by the value of the [`CMAKE_CXX_STANDARD_REQUIRED`](../variable/cmake_cxx_standard_required#variable:CMAKE_CXX_STANDARD_REQUIRED "CMAKE_CXX_STANDARD_REQUIRED") variable if it is set when a target is created.
cmake CUDA_RESOLVE_DEVICE_SYMBOLS CUDA\_RESOLVE\_DEVICE\_SYMBOLS
==============================
CUDA only: Enables device linking for the specific static library target
If set this will enable device linking on this static library target. Normally device linking is deferred until a shared library or executable is generated, allowing for multiple static libraries to resolve device symbols at the same time.
For instance:
```
set_property(TARGET mystaticlib PROPERTY CUDA_RESOLVE_DEVICE_SYMBOLS ON)
```
cmake ANDROID_ASSETS_DIRECTORIES ANDROID\_ASSETS\_DIRECTORIES
============================
Set the Android assets directories to copy into the main assets folder before build. This a string property that contains the directory paths separated by semicolon. This property is initialized by the value of the [`CMAKE_ANDROID_ASSETS_DIRECTORIES`](../variable/cmake_android_assets_directories#variable:CMAKE_ANDROID_ASSETS_DIRECTORIES "CMAKE_ANDROID_ASSETS_DIRECTORIES") variable if it is set when a target is created.
cmake IMPORTED_CONFIGURATIONS IMPORTED\_CONFIGURATIONS
========================
Configurations provided for an IMPORTED target.
Set this to the list of configuration names available for an IMPORTED target. The names correspond to configurations defined in the project from which the target is imported. If the importing project uses a different set of configurations the names may be mapped using the MAP\_IMPORTED\_CONFIG\_<CONFIG> property. Ignored for non-imported targets.
cmake IMPORTED_LINK_INTERFACE_LANGUAGES IMPORTED\_LINK\_INTERFACE\_LANGUAGES
====================================
Languages compiled into an IMPORTED static library.
Set this to the list of languages of source files compiled to produce a STATIC IMPORTED library (such as “C” or “CXX”). CMake accounts for these languages when computing how to link a target to the imported library. For example, when a C executable links to an imported C++ static library CMake chooses the C++ linker to satisfy language runtime dependencies of the static library.
This property is ignored for targets that are not STATIC libraries. This property is ignored for non-imported targets.
cmake COMPILE_PDB_OUTPUT_DIRECTORY COMPILE\_PDB\_OUTPUT\_DIRECTORY
===============================
Output directory for the MS debug symbol `.pdb` file generated by the compiler while building source files.
This property specifies the directory into which the MS debug symbols will be placed by the compiler. This property is initialized by the value of the [`CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY`](../variable/cmake_compile_pdb_output_directory#variable:CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY "CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY") variable if it is set when a target is created.
Note
The compiler-generated program database files are specified by the `/Fd` compiler flag and are not the same as linker-generated program database files specified by the `/pdb` linker flag. Use the [`PDB_OUTPUT_DIRECTORY`](pdb_output_directory#prop_tgt:PDB_OUTPUT_DIRECTORY "PDB_OUTPUT_DIRECTORY") property to specify the latter.
cmake AUTOUIC AUTOUIC
=======
Should the target be processed with autouic (for Qt projects).
`AUTOUIC` is a boolean specifying whether CMake will handle the Qt `uic` code generator automatically, i.e. without having to use the [`QT4_WRAP_UI()`](../module/findqt4#module:FindQt4 "FindQt4") or `QT5_WRAP_UI()` macro. Currently Qt4 and Qt5 are supported.
When this property is `ON`, CMake will scan the source files at build time and invoke `uic` accordingly. If an `#include` statement like `#include "ui_foo.h"` is found in `source.cpp`, a `foo.ui` file is searched for first in the vicinity of `source.cpp` and afterwards in the optional [`AUTOUIC_SEARCH_PATHS`](autouic_search_paths#prop_tgt:AUTOUIC_SEARCH_PATHS "AUTOUIC_SEARCH_PATHS") of the target. `uic` is run on the `foo.ui` file to generate `ui_foo.h` in the directory `<AUTOGEN_BUILD_DIR>/include`, which is automatically added to the target’s [`INCLUDE_DIRECTORIES`](include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES").
* See [`AUTOGEN_BUILD_DIR`](autogen_build_dir#prop_tgt:AUTOGEN_BUILD_DIR "AUTOGEN_BUILD_DIR").
This property is initialized by the value of the [`CMAKE_AUTOUIC`](../variable/cmake_autouic#variable:CMAKE_AUTOUIC "CMAKE_AUTOUIC") variable if it is set when a target is created.
Additional command line options for `uic` can be set via the [`AUTOUIC_OPTIONS`](../prop_sf/autouic_options#prop_sf:AUTOUIC_OPTIONS "AUTOUIC_OPTIONS") source file property on the `foo.ui` file. The global property [`AUTOGEN_TARGETS_FOLDER`](../prop_gbl/autogen_targets_folder#prop_gbl:AUTOGEN_TARGETS_FOLDER "AUTOGEN_TARGETS_FOLDER") can be used to group the autouic targets together in an IDE, e.g. in MSVS.
Source files can be excluded from [`AUTOUIC`](#prop_tgt:AUTOUIC "AUTOUIC") processing by enabling [`SKIP_AUTOUIC`](../prop_sf/skip_autouic#prop_sf:SKIP_AUTOUIC "SKIP_AUTOUIC") or the broader [`SKIP_AUTOGEN`](../prop_sf/skip_autogen#prop_sf:SKIP_AUTOGEN "SKIP_AUTOGEN").
See the [`cmake-qt(7)`](../manual/cmake-qt.7#manual:cmake-qt(7) "cmake-qt(7)") manual for more information on using CMake with Qt.
cmake ANDROID_API_MIN ANDROID\_API\_MIN
=================
Set the Android MIN API version (e.g. `9`). The version number must be a positive decimal integer. This property is initialized by the value of the [`CMAKE_ANDROID_API_MIN`](../variable/cmake_android_api_min#variable:CMAKE_ANDROID_API_MIN "CMAKE_ANDROID_API_MIN") variable if it is set when a target is created. Native code builds using this API version.
cmake ANDROID_API ANDROID\_API
============
When [Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio Edition](../manual/cmake-toolchains.7#cross-compiling-for-android-with-nvidia-nsight-tegra-visual-studio-edition), this property sets the Android target API version (e.g. `15`). The version number must be a positive decimal integer. This property is initialized by the value of the [`CMAKE_ANDROID_API`](../variable/cmake_android_api#variable:CMAKE_ANDROID_API "CMAKE_ANDROID_API") variable if it is set when a target is created.
cmake NO_SONAME NO\_SONAME
==========
Whether to set “soname” when linking a shared library.
Enable this boolean property if a generated shared library should not have “soname” set. Default is to set “soname” on all shared libraries as long as the platform supports it. Generally, use this property only for leaf private libraries or plugins. If you use it on normal shared libraries which other targets link against, on some platforms a linker will insert a full path to the library (as specified at link time) into the dynamic section of the dependent binary. Therefore, once installed, dynamic loader may eventually fail to locate the library for the binary.
cmake VS_SCC_PROVIDER VS\_SCC\_PROVIDER
=================
Visual Studio Source Code Control Provider.
Can be set to change the visual studio source code control provider property.
cmake VS_DOTNET_REFERENCE_<refname> VS\_DOTNET\_REFERENCE\_<refname>
================================
Visual Studio managed project .NET reference with name `<refname>` and hint path.
Adds one .NET reference to generated Visual Studio project. The reference will have the name `<refname>` and will point to the assembly given as value of the property.
See also [`VS_DOTNET_REFERENCES`](vs_dotnet_references#prop_tgt:VS_DOTNET_REFERENCES "VS_DOTNET_REFERENCES") and [`VS_DOTNET_REFERENCES_COPY_LOCAL`](vs_dotnet_references_copy_local#prop_tgt:VS_DOTNET_REFERENCES_COPY_LOCAL "VS_DOTNET_REFERENCES_COPY_LOCAL")
cmake ARCHIVE_OUTPUT_DIRECTORY ARCHIVE\_OUTPUT\_DIRECTORY
==========================
Output directory in which to build [ARCHIVE](../manual/cmake-buildsystem.7#archive-output-artifacts) target files.
This property specifies the directory into which archive target files should be built. The property value may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)"). Multi-configuration generators (VS, Xcode) append a per-configuration subdirectory to the specified directory unless a generator expression is used.
This property is initialized by the value of the variable CMAKE\_ARCHIVE\_OUTPUT\_DIRECTORY if it is set when a target is created.
See also the [`ARCHIVE_OUTPUT_DIRECTORY_<CONFIG>`](# "ARCHIVE_OUTPUT_DIRECTORY_<CONFIG>") target property.
cmake INTERFACE_COMPILE_FEATURES INTERFACE\_COMPILE\_FEATURES
============================
List of public compile features requirements for a library.
Targets may populate this property to publish the compile features required to compile against the headers for the target. The [`target_compile_features()`](../command/target_compile_features#command:target_compile_features "target_compile_features") command populates this property with values given to the `PUBLIC` and `INTERFACE` keywords. Projects may also get and set the property directly.
When target dependencies are specified using [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries"), CMake will read this property from all target dependencies to determine the build properties of the consumer.
Contents of `INTERFACE_COMPILE_FEATURES` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") -manual for more on defining buildsystem properties.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
cmake XCODE_PRODUCT_TYPE XCODE\_PRODUCT\_TYPE
====================
Set the Xcode `productType` attribute on its reference to a target. CMake computes a default based on target type but can be told explicitly with this property.
See also [`XCODE_EXPLICIT_FILE_TYPE`](xcode_explicit_file_type#prop_tgt:XCODE_EXPLICIT_FILE_TYPE "XCODE_EXPLICIT_FILE_TYPE").
cmake IMPORTED_LINK_DEPENDENT_LIBRARIES IMPORTED\_LINK\_DEPENDENT\_LIBRARIES
====================================
Dependent shared libraries of an imported shared library.
Shared libraries may be linked to other shared libraries as part of their implementation. On some platforms the linker searches for the dependent libraries of shared libraries they are including in the link. Set this property to the list of dependent shared libraries of an imported library. The list should be disjoint from the list of interface libraries in the INTERFACE\_LINK\_LIBRARIES property. On platforms requiring dependent shared libraries to be found at link time CMake uses this list to add appropriate files or paths to the link command line. Ignored for non-imported targets.
cmake PDB_OUTPUT_DIRECTORY PDB\_OUTPUT\_DIRECTORY
======================
Output directory for the MS debug symbols `.pdb` file generated by the linker for an executable or shared library target.
This property specifies the directory into which the MS debug symbols will be placed by the linker. This property is initialized by the value of the [`CMAKE_PDB_OUTPUT_DIRECTORY`](../variable/cmake_pdb_output_directory#variable:CMAKE_PDB_OUTPUT_DIRECTORY "CMAKE_PDB_OUTPUT_DIRECTORY") variable if it is set when a target is created.
Note
This property does not apply to STATIC library targets because no linker is invoked to produce them so they have no linker-generated `.pdb` file containing debug symbols.
The linker-generated program database files are specified by the `/pdb` linker flag and are not the same as compiler-generated program database files specified by the `/Fd` compiler flag. Use the [`COMPILE_PDB_OUTPUT_DIRECTORY`](compile_pdb_output_directory#prop_tgt:COMPILE_PDB_OUTPUT_DIRECTORY "COMPILE_PDB_OUTPUT_DIRECTORY") property to specify the latter.
cmake COMPILE_FEATURES COMPILE\_FEATURES
=================
Compiler features enabled for this target.
The list of features in this property are a subset of the features listed in the [`CMAKE_CXX_COMPILE_FEATURES`](../variable/cmake_cxx_compile_features#variable:CMAKE_CXX_COMPILE_FEATURES "CMAKE_CXX_COMPILE_FEATURES") variable.
Contents of `COMPILE_FEATURES` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
cmake VS_DOTNET_TARGET_FRAMEWORK_VERSION VS\_DOTNET\_TARGET\_FRAMEWORK\_VERSION
======================================
Specify the .NET target framework version.
Used to specify the .NET target framework version for C++/CLI. For example, “v4.5”.
cmake ANDROID_NATIVE_LIB_DIRECTORIES ANDROID\_NATIVE\_LIB\_DIRECTORIES
=================================
Set the Android property that specifies directories to search for the .so libraries.
This a string property that contains the directory paths separated by semicolons.
This property is initialized by the value of the [`CMAKE_ANDROID_NATIVE_LIB_DIRECTORIES`](../variable/cmake_android_native_lib_directories#variable:CMAKE_ANDROID_NATIVE_LIB_DIRECTORIES "CMAKE_ANDROID_NATIVE_LIB_DIRECTORIES") variable if it is set when a target is created.
Contents of `ANDROID_NATIVE_LIB_DIRECTORIES` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions.
cmake ANDROID_GUI ANDROID\_GUI
============
When [Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio Edition](../manual/cmake-toolchains.7#cross-compiling-for-android-with-nvidia-nsight-tegra-visual-studio-edition), this property specifies whether to build an executable as an application package on Android.
When this property is set to true the executable when built for Android will be created as an application package. This property is initialized by the value of the [`CMAKE_ANDROID_GUI`](../variable/cmake_android_gui#variable:CMAKE_ANDROID_GUI "CMAKE_ANDROID_GUI") variable if it is set when a target is created.
Add the `AndroidManifest.xml` source file explicitly to the target [`add_executable()`](../command/add_executable#command:add_executable "add_executable") command invocation to specify the root directory of the application package source.
cmake LIBRARY_OUTPUT_DIRECTORY LIBRARY\_OUTPUT\_DIRECTORY
==========================
Output directory in which to build [LIBRARY](../manual/cmake-buildsystem.7#library-output-artifacts) target files.
This property specifies the directory into which library target files should be built. The property value may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)"). Multi-configuration generators (VS, Xcode) append a per-configuration subdirectory to the specified directory unless a generator expression is used.
This property is initialized by the value of the variable CMAKE\_LIBRARY\_OUTPUT\_DIRECTORY if it is set when a target is created.
See also the [`LIBRARY_OUTPUT_DIRECTORY_<CONFIG>`](# "LIBRARY_OUTPUT_DIRECTORY_<CONFIG>") target property.
| programming_docs |
cmake AUTOMOC_MOC_OPTIONS AUTOMOC\_MOC\_OPTIONS
=====================
Additional options for moc when using [`AUTOMOC`](automoc#prop_tgt:AUTOMOC "AUTOMOC")
This property is only used if the [`AUTOMOC`](automoc#prop_tgt:AUTOMOC "AUTOMOC") property is `ON` for this target. In this case, it holds additional command line options which will be used when `moc` is executed during the build, i.e. it is equivalent to the optional `OPTIONS` argument of the [`qt4_wrap_cpp()`](../module/findqt4#module:FindQt4 "FindQt4") macro.
By default it is empty.
See the [`cmake-qt(7)`](../manual/cmake-qt.7#manual:cmake-qt(7) "cmake-qt(7)") manual for more information on using CMake with Qt.
cmake <LANG>_CPPLINT <LANG>\_CPPLINT
===============
This property is supported only when `<LANG>` is `C` or `CXX`.
Specify a [;-list](../manual/cmake-language.7#cmake-language-lists) containing a command line for the `cpplint` style checker. The [Makefile Generators](../manual/cmake-generators.7#makefile-generators) and the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator will run `cpplint` along with the compiler and report any problems.
This property is initialized by the value of the [`CMAKE_<LANG>_CPPLINT`](# "CMAKE_<LANG>_CPPLINT") variable if it is set when a target is created.
cmake PDB_NAME_<CONFIG> PDB\_NAME\_<CONFIG>
===================
Per-configuration output name for the MS debug symbol `.pdb` file generated by the linker for an executable or shared library target.
This is the configuration-specific version of [`PDB_NAME`](pdb_name#prop_tgt:PDB_NAME "PDB_NAME").
Note
This property does not apply to STATIC library targets because no linker is invoked to produce them so they have no linker-generated `.pdb` file containing debug symbols.
The linker-generated program database files are specified by the `/pdb` linker flag and are not the same as compiler-generated program database files specified by the `/Fd` compiler flag. Use the [`COMPILE_PDB_NAME_<CONFIG>`](# "COMPILE_PDB_NAME_<CONFIG>") property to specify the latter.
cmake INTERFACE_LINK_LIBRARIES INTERFACE\_LINK\_LIBRARIES
==========================
List public interface libraries for a library.
This property contains the list of transitive link dependencies. When the target is linked into another target using the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command, the libraries listed (and recursively their link interface libraries) will be provided to the other target also. This property is overridden by the [`LINK_INTERFACE_LIBRARIES`](link_interface_libraries#prop_tgt:LINK_INTERFACE_LIBRARIES "LINK_INTERFACE_LIBRARIES") or [`LINK_INTERFACE_LIBRARIES_<CONFIG>`](# "LINK_INTERFACE_LIBRARIES_<CONFIG>") property if policy [`CMP0022`](../policy/cmp0022#policy:CMP0022 "CMP0022") is `OLD` or unset.
Contents of `INTERFACE_LINK_LIBRARIES` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
Creating Relocatable Packages
-----------------------------
Note that it is not advisable to populate the `INTERFACE_LINK_LIBRARIES` of a target with absolute paths to dependencies. That would hard-code into installed packages the library file paths for dependencies **as found on the machine the package was made on**.
See the [Creating Relocatable Packages](../manual/cmake-packages.7#creating-relocatable-packages) section of the [`cmake-packages(7)`](../manual/cmake-packages.7#manual:cmake-packages(7) "cmake-packages(7)") manual for discussion of additional care that must be taken when specifying usage requirements while creating packages for redistribution.
cmake XCODE_ATTRIBUTE_<an-attribute> XCODE\_ATTRIBUTE\_<an-attribute>
================================
Set Xcode target attributes directly.
Tell the Xcode generator to set ‘<an-attribute>’ to a given value in the generated Xcode project. Ignored on other generators.
See the [`CMAKE_XCODE_ATTRIBUTE_<an-attribute>`](# "CMAKE_XCODE_ATTRIBUTE_<an-attribute>") variable to set attributes on all targets in a directory tree.
Contents of `XCODE_ATTRIBUTE_<an-attribute>` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake ANDROID_JAVA_SOURCE_DIR ANDROID\_JAVA\_SOURCE\_DIR
==========================
Set the Android property that defines the Java source code root directories. This a string property that contains the directory paths separated by semicolon. This property is initialized by the value of the [`CMAKE_ANDROID_JAVA_SOURCE_DIR`](../variable/cmake_android_java_source_dir#variable:CMAKE_ANDROID_JAVA_SOURCE_DIR "CMAKE_ANDROID_JAVA_SOURCE_DIR") variable if it is set when a target is created.
cmake IMPORTED_LIBNAME IMPORTED\_LIBNAME
=================
Specify the link library name for an [imported](../manual/cmake-buildsystem.7#imported-targets) [Interface Library](../manual/cmake-buildsystem.7#interface-libraries).
An interface library builds no library file itself but does specify usage requirements for its consumers. The `IMPORTED_LIBNAME` property may be set to specify a single library name to be placed on the link line in place of the interface library target name as a requirement for using the interface.
This property is intended for use in naming libraries provided by a platform SDK for which the full path to a library file may not be known. The value may be a plain library name such as `foo` but may *not* be a path (e.g. `/usr/lib/libfoo.so`) or a flag (e.g. `-Wl,...`). The name is never treated as a library target name even if it happens to name one.
The `IMPORTED_LIBNAME` property is allowed only on [imported](../manual/cmake-buildsystem.7#imported-targets) [Interface Libraries](../manual/cmake-buildsystem.7#interface-libraries) and is rejected on targets of other types (for which the [`IMPORTED_LOCATION`](imported_location#prop_tgt:IMPORTED_LOCATION "IMPORTED_LOCATION") target property may be used).
cmake INTERFACE_INCLUDE_DIRECTORIES INTERFACE\_INCLUDE\_DIRECTORIES
===============================
List of public include directories requirements for a library.
Targets may populate this property to publish the include directories required to compile against the headers for the target. The [`target_include_directories()`](../command/target_include_directories#command:target_include_directories "target_include_directories") command populates this property with values given to the `PUBLIC` and `INTERFACE` keywords. Projects may also get and set the property directly.
When target dependencies are specified using [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries"), CMake will read this property from all target dependencies to determine the build properties of the consumer.
Contents of `INTERFACE_INCLUDE_DIRECTORIES` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") -manual for more on defining buildsystem properties.
Include directories usage requirements commonly differ between the build-tree and the install-tree. The `BUILD_INTERFACE` and `INSTALL_INTERFACE` generator expressions can be used to describe separate usage requirements based on the usage location. Relative paths are allowed within the `INSTALL_INTERFACE` expression and are interpreted relative to the installation prefix. For example:
```
target_include_directories(mylib INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/mylib>
$<INSTALL_INTERFACE:include/mylib> # <prefix>/include/mylib
)
```
Creating Relocatable Packages
-----------------------------
Note that it is not advisable to populate the `INSTALL_INTERFACE` of the `INTERFACE_INCLUDE_DIRECTORIES` of a target with absolute paths to the include directories of dependencies. That would hard-code into installed packages the include directory paths for dependencies **as found on the machine the package was made on**.
The `INSTALL_INTERFACE` of the `INTERFACE_INCLUDE_DIRECTORIES` is only suitable for specifying the required include directories for headers provided with the target itself, not those provided by the transitive dependencies listed in its [`INTERFACE_LINK_LIBRARIES`](interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES") target property. Those dependencies should themselves be targets that specify their own header locations in `INTERFACE_INCLUDE_DIRECTORIES`.
See the [Creating Relocatable Packages](../manual/cmake-packages.7#creating-relocatable-packages) section of the [`cmake-packages(7)`](../manual/cmake-packages.7#manual:cmake-packages(7) "cmake-packages(7)") manual for discussion of additional care that must be taken when specifying usage requirements while creating packages for redistribution.
cmake JOB_POOL_LINK JOB\_POOL\_LINK
===============
Ninja only: Pool used for linking.
The number of parallel link processes could be limited by defining pools with the global [`JOB_POOLS`](../prop_gbl/job_pools#prop_gbl:JOB_POOLS "JOB_POOLS") property and then specifying here the pool name.
For instance:
```
set_property(TARGET myexe PROPERTY JOB_POOL_LINK two_jobs)
```
This property is initialized by the value of [`CMAKE_JOB_POOL_LINK`](../variable/cmake_job_pool_link#variable:CMAKE_JOB_POOL_LINK "CMAKE_JOB_POOL_LINK").
cmake INCLUDE_DIRECTORIES INCLUDE\_DIRECTORIES
====================
List of preprocessor include file search directories.
This property specifies the list of directories given so far to the [`target_include_directories()`](../command/target_include_directories#command:target_include_directories "target_include_directories") command. In addition to accepting values from that command, values may be set directly on any target using the [`set_property()`](../command/set_property#command:set_property "set_property") command. A target gets its initial value for this property from the value of the [`INCLUDE_DIRECTORIES`](../prop_dir/include_directories#prop_dir:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES") directory property. Both directory and target property values are adjusted by calls to the [`include_directories()`](../command/include_directories#command:include_directories "include_directories") command.
The value of this property is used by the generators to set the include paths for the compiler.
Relative paths should not be added to this property directly. Use one of the commands above instead to handle relative paths.
Contents of `INCLUDE_DIRECTORIES` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake CROSSCOMPILING_EMULATOR CROSSCOMPILING\_EMULATOR
========================
Use the given emulator to run executables created when crosscompiling. This command will be added as a prefix to [`add_test()`](../command/add_test#command:add_test "add_test"), [`add_custom_command()`](../command/add_custom_command#command:add_custom_command "add_custom_command"), and [`add_custom_target()`](../command/add_custom_target#command:add_custom_target "add_custom_target") commands for built target system executables.
This property is initialized by the value of the [`CMAKE_CROSSCOMPILING_EMULATOR`](../variable/cmake_crosscompiling_emulator#variable:CMAKE_CROSSCOMPILING_EMULATOR "CMAKE_CROSSCOMPILING_EMULATOR") variable if it is set when a target is created.
cmake VS_GLOBAL_ROOTNAMESPACE VS\_GLOBAL\_ROOTNAMESPACE
=========================
Visual Studio project root namespace.
Sets the “RootNamespace” attribute for a generated Visual Studio project. The attribute will be generated only if this is set.
cmake LOCATION_<CONFIG> LOCATION\_<CONFIG>
==================
Read-only property providing a target location on disk.
A read-only property that indicates where a target’s main file is located on disk for the configuration <CONFIG>. The property is defined only for library and executable targets. An imported target may provide a set of configurations different from that of the importing project. By default CMake looks for an exact-match but otherwise uses an arbitrary available configuration. Use the MAP\_IMPORTED\_CONFIG\_<CONFIG> property to map imported configurations explicitly.
Do not set properties that affect the location of a target after reading this property. These include properties whose names match “(RUNTIME|LIBRARY|ARCHIVE)\_OUTPUT\_(NAME|DIRECTORY)(\_<CONFIG>)?”, `(IMPLIB_)?(PREFIX|SUFFIX)`, or “LINKER\_LANGUAGE”. Failure to follow this rule is not diagnosed and leaves the location of the target undefined.
cmake VS_IOT_EXTENSIONS_VERSION VS\_IOT\_EXTENSIONS\_VERSION
============================
Visual Studio Windows 10 IoT Extensions Version
Specifies the version of the IoT Extensions that should be included in the target. For example `10.0.10240.0`. If the value is not specified, the IoT Extensions will not be included. To use the same version of the extensions as the Windows 10 SDK that is being used, you can use the [`CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION`](../variable/cmake_vs_windows_target_platform_version#variable:CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION "CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION") variable.
cmake OSX_ARCHITECTURES OSX\_ARCHITECTURES
==================
Target specific architectures for OS X.
The `OSX_ARCHITECTURES` property sets the target binary architecture for targets on OS X (`-arch`). This property is initialized by the value of the variable [`CMAKE_OSX_ARCHITECTURES`](../variable/cmake_osx_architectures#variable:CMAKE_OSX_ARCHITECTURES "CMAKE_OSX_ARCHITECTURES") if it is set when a target is created. Use [`OSX_ARCHITECTURES_<CONFIG>`](# "OSX_ARCHITECTURES_<CONFIG>") to set the binary architectures on a per-configuration basis, where `<CONFIG>` is an upper-case name (e.g. `OSX_ARCHITECTURES_DEBUG`).
cmake CXX_STANDARD CXX\_STANDARD
=============
The C++ standard whose features are requested to build this target.
This property specifies the C++ standard whose features are requested to build this target. For some compilers, this results in adding a flag such as `-std=gnu++11` to the compile line. For compilers that have no notion of a standard level, such as MSVC, this has no effect.
Supported values are `98`, `11`, `14`, and `17`.
If the value requested does not result in a compile flag being added for the compiler in use, a previous standard flag will be added instead. This means that using:
```
set_property(TARGET tgt PROPERTY CXX_STANDARD 11)
```
with a compiler which does not support `-std=gnu++11` or an equivalent flag will not result in an error or warning, but will instead add the `-std=gnu++98` flag if supported. This “decay” behavior may be controlled with the [`CXX_STANDARD_REQUIRED`](cxx_standard_required#prop_tgt:CXX_STANDARD_REQUIRED "CXX_STANDARD_REQUIRED") target property. Additionally, the [`CXX_EXTENSIONS`](cxx_extensions#prop_tgt:CXX_EXTENSIONS "CXX_EXTENSIONS") target property may be used to control whether compiler-specific extensions are enabled on a per-target basis.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
This property is initialized by the value of the [`CMAKE_CXX_STANDARD`](../variable/cmake_cxx_standard#variable:CMAKE_CXX_STANDARD "CMAKE_CXX_STANDARD") variable if it is set when a target is created.
cmake GENERATOR_FILE_NAME GENERATOR\_FILE\_NAME
=====================
Generator’s file for this target.
An internal property used by some generators to record the name of the project or dsp file associated with this target. Note that at configure time, this property is only set for targets created by include\_external\_msproject().
cmake IMPORT_PREFIX IMPORT\_PREFIX
==============
What comes before the import library name.
Similar to the target property PREFIX, but used for import libraries (typically corresponding to a DLL) instead of regular libraries. A target property that can be set to override the prefix (such as “lib”) on an import library name.
cmake ENABLE_EXPORTS ENABLE\_EXPORTS
===============
Specify whether an executable exports symbols for loadable modules.
Normally an executable does not export any symbols because it is the final program. It is possible for an executable to export symbols to be used by loadable modules. When this property is set to true CMake will allow other targets to “link” to the executable with the [`TARGET_LINK_LIBRARIES()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command. On all platforms a target-level dependency on the executable is created for targets that link to it. For DLL platforms an import library will be created for the exported symbols and then used for linking. All Windows-based systems including Cygwin are DLL platforms. For non-DLL platforms that require all symbols to be resolved at link time, such as OS X, the module will “link” to the executable using a flag like `-bundle_loader`. For other non-DLL platforms the link rule is simply ignored since the dynamic loader will automatically bind symbols when the module is loaded.
This property is initialized by the value of the variable [`CMAKE_ENABLE_EXPORTS`](../variable/cmake_enable_exports#variable:CMAKE_ENABLE_EXPORTS "CMAKE_ENABLE_EXPORTS") if it is set when a target is created.
cmake RULE_LAUNCH_LINK RULE\_LAUNCH\_LINK
==================
Specify a launcher for link rules.
See the global property of the same name for details. This overrides the global and directory property for a target.
cmake RUNTIME_OUTPUT_NAME_<CONFIG> RUNTIME\_OUTPUT\_NAME\_<CONFIG>
===============================
Per-configuration output name for [RUNTIME](../manual/cmake-buildsystem.7#runtime-output-artifacts) target files.
This is the configuration-specific version of the [`RUNTIME_OUTPUT_NAME`](runtime_output_name#prop_tgt:RUNTIME_OUTPUT_NAME "RUNTIME_OUTPUT_NAME") target property.
cmake COMPILE_PDB_OUTPUT_DIRECTORY_<CONFIG> COMPILE\_PDB\_OUTPUT\_DIRECTORY\_<CONFIG>
=========================================
Per-configuration output directory for the MS debug symbol `.pdb` file generated by the compiler while building source files.
This is a per-configuration version of [`COMPILE_PDB_OUTPUT_DIRECTORY`](compile_pdb_output_directory#prop_tgt:COMPILE_PDB_OUTPUT_DIRECTORY "COMPILE_PDB_OUTPUT_DIRECTORY"), but multi-configuration generators (VS, Xcode) do NOT append a per-configuration subdirectory to the specified directory. This property is initialized by the value of the [`CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY_<CONFIG>`](# "CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY_<CONFIG>") variable if it is set when a target is created.
Note
The compiler-generated program database files are specified by the `/Fd` compiler flag and are not the same as linker-generated program database files specified by the `/pdb` linker flag. Use the [`PDB_OUTPUT_DIRECTORY_<CONFIG>`](# "PDB_OUTPUT_DIRECTORY_<CONFIG>") property to specify the latter.
| programming_docs |
cmake WINDOWS_EXPORT_ALL_SYMBOLS WINDOWS\_EXPORT\_ALL\_SYMBOLS
=============================
This property is implemented only for MS-compatible tools on Windows.
Enable this boolean property to automatically create a module definition (`.def`) file with all global symbols found in the input `.obj` files for a `SHARED` library (or executable with [`ENABLE_EXPORTS`](enable_exports#prop_tgt:ENABLE_EXPORTS "ENABLE_EXPORTS")) on Windows. The module definition file will be passed to the linker causing all symbols to be exported from the `.dll`. For global *data* symbols, `__declspec(dllimport)` must still be used when compiling against the code in the `.dll`. All other function symbols will be automatically exported and imported by callers. This simplifies porting projects to Windows by reducing the need for explicit `dllexport` markup, even in `C++` classes.
When this property is enabled, zero or more `.def` files may also be specified as source files of the target. The exports named by these files will be merged with those detected from the object files to generate a single module definition file to be passed to the linker. This can be used to export symbols from a `.dll` that are not in any of its object files but are added by the linker from dependencies (e.g. `msvcrt.lib`).
This property is initialized by the value of the [`CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS`](../variable/cmake_windows_export_all_symbols#variable:CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS "CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS") variable if it is set when a target is created.
cmake INSTALL_NAME_DIR INSTALL\_NAME\_DIR
==================
Mac OSX directory name for installed targets.
INSTALL\_NAME\_DIR is a string specifying the directory portion of the “install\_name” field of shared libraries on Mac OSX to use in the installed targets.
cmake NO_SYSTEM_FROM_IMPORTED NO\_SYSTEM\_FROM\_IMPORTED
==========================
Do not treat includes from IMPORTED target interfaces as SYSTEM.
The contents of the INTERFACE\_INCLUDE\_DIRECTORIES of IMPORTED targets are treated as SYSTEM includes by default. If this property is enabled, the contents of the INTERFACE\_INCLUDE\_DIRECTORIES of IMPORTED targets are not treated as system includes. This property is initialized by the value of the variable CMAKE\_NO\_SYSTEM\_FROM\_IMPORTED if it is set when a target is created.
cmake IMPORTED_LINK_INTERFACE_MULTIPLICITY_<CONFIG> IMPORTED\_LINK\_INTERFACE\_MULTIPLICITY\_<CONFIG>
=================================================
<CONFIG>-specific version of IMPORTED\_LINK\_INTERFACE\_MULTIPLICITY.
If set, this property completely overrides the generic property for the named configuration.
cmake ANDROID_PROCESS_MAX ANDROID\_PROCESS\_MAX
=====================
Set the Android property that defines the maximum number of a parallel Android NDK compiler processes (e.g. `4`). This property is initialized by the value of the [`CMAKE_ANDROID_PROCESS_MAX`](../variable/cmake_android_process_max#variable:CMAKE_ANDROID_PROCESS_MAX "CMAKE_ANDROID_PROCESS_MAX") variable if it is set when a target is created.
cmake GNUtoMS GNUtoMS
=======
Convert GNU import library (.dll.a) to MS format (.lib).
When linking a shared library or executable that exports symbols using GNU tools on Windows (MinGW/MSYS) with Visual Studio installed convert the import library (.dll.a) from GNU to MS format (.lib). Both import libraries will be installed by install(TARGETS) and exported by install(EXPORT) and export() to be linked by applications with either GNU- or MS-compatible tools.
If the variable CMAKE\_GNUtoMS is set when a target is created its value is used to initialize this property. The variable must be set prior to the first command that enables a language such as project() or enable\_language(). CMake provides the variable as an option to the user automatically when configuring on Windows with GNU tools.
cmake <LANG>_VISIBILITY_PRESET <LANG>\_VISIBILITY\_PRESET
==========================
Value for symbol visibility compile flags
The `<LANG>_VISIBILITY_PRESET` property determines the value passed in a visibility related compile option, such as `-fvisibility=` for `<LANG>`. This property affects compilation in sources of all types of targets (subject to policy [`CMP0063`](../policy/cmp0063#policy:CMP0063 "CMP0063")).
This property is initialized by the value of the [`CMAKE_<LANG>_VISIBILITY_PRESET`](# "CMAKE_<LANG>_VISIBILITY_PRESET") variable if it is set when a target is created.
cmake NAME NAME
====
Logical name for the target.
Read-only logical name for the target as used by CMake.
cmake LOCATION LOCATION
========
Read-only location of a target on disk.
For an imported target, this read-only property returns the value of the LOCATION\_<CONFIG> property for an unspecified configuration <CONFIG> provided by the target.
For a non-imported target, this property is provided for compatibility with CMake 2.4 and below. It was meant to get the location of an executable target’s output file for use in add\_custom\_command. The path may contain a build-system-specific portion that is replaced at build time with the configuration getting built (such as “$(ConfigurationName)” in VS). In CMake 2.6 and above add\_custom\_command automatically recognizes a target name in its COMMAND and DEPENDS options and computes the target location. In CMake 2.8.4 and above add\_custom\_command recognizes generator expressions to refer to target locations anywhere in the command. Therefore this property is not needed for creating custom commands.
Do not set properties that affect the location of a target after reading this property. These include properties whose names match “(RUNTIME|LIBRARY|ARCHIVE)\_OUTPUT\_(NAME|DIRECTORY)(\_<CONFIG>)?”, `(IMPLIB_)?(PREFIX|SUFFIX)`, or “LINKER\_LANGUAGE”. Failure to follow this rule is not diagnosed and leaves the location of the target undefined.
cmake ARCHIVE_OUTPUT_DIRECTORY_<CONFIG> ARCHIVE\_OUTPUT\_DIRECTORY\_<CONFIG>
====================================
Per-configuration output directory for [ARCHIVE](../manual/cmake-buildsystem.7#archive-output-artifacts) target files.
This is a per-configuration version of the [`ARCHIVE_OUTPUT_DIRECTORY`](archive_output_directory#prop_tgt:ARCHIVE_OUTPUT_DIRECTORY "ARCHIVE_OUTPUT_DIRECTORY") target property, but multi-configuration generators (VS, Xcode) do NOT append a per-configuration subdirectory to the specified directory. This property is initialized by the value of the [`CMAKE_ARCHIVE_OUTPUT_DIRECTORY_<CONFIG>`](# "CMAKE_ARCHIVE_OUTPUT_DIRECTORY_<CONFIG>") variable if it is set when a target is created.
Contents of `ARCHIVE_OUTPUT_DIRECTORY_<CONFIG>` may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)").
cmake AUTOMOC AUTOMOC
=======
Should the target be processed with automoc (for Qt projects).
AUTOMOC is a boolean specifying whether CMake will handle the Qt `moc` preprocessor automatically, i.e. without having to use the [`QT4_WRAP_CPP()`](../module/findqt4#module:FindQt4 "FindQt4") or QT5\_WRAP\_CPP() macro. Currently Qt4 and Qt5 are supported.
When this property is set `ON`, CMake will scan the header and source files at build time and invoke moc accordingly.
* If an `#include` statement like `#include "moc_<basename>.cpp"` is found, the `Q_OBJECT` or `Q_GADGET` macros are expected in an otherwise empty line of the `<basename>.h(xx)` header file. `moc` is run on the header file to generate `moc_<basename>.cpp` in the `<AUTOGEN_BUILD_DIR>/include` directory which is automatically added to the target’s [`INCLUDE_DIRECTORIES`](include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES"). This allows the compiler to find the included `moc_<basename>.cpp` file regardless of the location the original source.
+ See [`AUTOGEN_BUILD_DIR`](autogen_build_dir#prop_tgt:AUTOGEN_BUILD_DIR "AUTOGEN_BUILD_DIR").
* If an `#include` statement like `#include "<basename>.moc"` is found, then `Q_OBJECT` or `Q_GADGET` macros are expected in the current source file and `moc` is run on the source file itself.
* Header files that are not included by an `#include "moc_<basename>.cpp"` statement are nonetheless scanned for `Q_OBJECT` or `Q_GADGET` macros. The resulting `moc_<basename>.cpp` files are generated in custom directories and automatically included in a generated `<AUTOGEN_BUILD_DIR>/mocs_compilation.cpp` file, which is compiled as part of the target.
+ The custom directories with checksum based names help to avoid name collisions for moc files with the same `<basename>`.
+ See [`AUTOGEN_BUILD_DIR`](autogen_build_dir#prop_tgt:AUTOGEN_BUILD_DIR "AUTOGEN_BUILD_DIR").
* Additionally, header files with the same base name as a source file, (like `<basename>.h`) or `_p` appended to the base name (like `<basename>_p.h`), are parsed for `Q_OBJECT` or `Q_GADGET` macros, and if found, `moc` is also executed on those files.
* `AUTOMOC` always checks multiple header alternative extensions, such as `hpp`, `hxx`, etc. when searching for headers.
* `AUTOMOC` looks for the `Q_PLUGIN_METADATA` macro and reruns the `moc` when the file addressed by the `FILE` argument of the macro changes.
This property is initialized by the value of the [`CMAKE_AUTOMOC`](../variable/cmake_automoc#variable:CMAKE_AUTOMOC "CMAKE_AUTOMOC") variable if it is set when a target is created.
Additional command line options for moc can be set via the [`AUTOMOC_MOC_OPTIONS`](automoc_moc_options#prop_tgt:AUTOMOC_MOC_OPTIONS "AUTOMOC_MOC_OPTIONS") property.
By enabling the [`CMAKE_AUTOMOC_RELAXED_MODE`](../variable/cmake_automoc_relaxed_mode#variable:CMAKE_AUTOMOC_RELAXED_MODE "CMAKE_AUTOMOC_RELAXED_MODE") variable the rules for searching the files which will be processed by moc can be relaxed. See the documentation for this variable for more details.
The global property [`AUTOGEN_TARGETS_FOLDER`](../prop_gbl/autogen_targets_folder#prop_gbl:AUTOGEN_TARGETS_FOLDER "AUTOGEN_TARGETS_FOLDER") can be used to group the automoc targets together in an IDE, e.g. in MSVS.
The global property [`AUTOGEN_SOURCE_GROUP`](../prop_gbl/autogen_source_group#prop_gbl:AUTOGEN_SOURCE_GROUP "AUTOGEN_SOURCE_GROUP") can be used to group files generated by [`AUTOMOC`](#prop_tgt:AUTOMOC "AUTOMOC") together in an IDE, e.g. in MSVS.
Additional `moc` dependency file names can be extracted from source code by using [`AUTOMOC_DEPEND_FILTERS`](automoc_depend_filters#prop_tgt:AUTOMOC_DEPEND_FILTERS "AUTOMOC_DEPEND_FILTERS").
Source C++ files can be excluded from [`AUTOMOC`](#prop_tgt:AUTOMOC "AUTOMOC") processing by enabling [`SKIP_AUTOMOC`](../prop_sf/skip_automoc#prop_sf:SKIP_AUTOMOC "SKIP_AUTOMOC") or the broader [`SKIP_AUTOGEN`](../prop_sf/skip_autogen#prop_sf:SKIP_AUTOGEN "SKIP_AUTOGEN").
See the [`cmake-qt(7)`](../manual/cmake-qt.7#manual:cmake-qt(7) "cmake-qt(7)") manual for more information on using CMake with Qt.
cmake DEFINE_SYMBOL DEFINE\_SYMBOL
==============
Define a symbol when compiling this target’s sources.
DEFINE\_SYMBOL sets the name of the preprocessor symbol defined when compiling sources in a shared library. If not set here then it is set to target\_EXPORTS by default (with some substitutions if the target is not a valid C identifier). This is useful for headers to know whether they are being included from inside their library or outside to properly setup dllexport/dllimport decorations.
cmake MACOSX_RPATH MACOSX\_RPATH
=============
Whether this target on OS X or iOS is located at runtime using rpaths.
When this property is set to `TRUE`, the directory portion of the `install_name` field of this shared library will be `@rpath` unless overridden by [`INSTALL_NAME_DIR`](install_name_dir#prop_tgt:INSTALL_NAME_DIR "INSTALL_NAME_DIR"). This indicates the shared library is to be found at runtime using runtime paths (rpaths).
This property is initialized by the value of the variable [`CMAKE_MACOSX_RPATH`](../variable/cmake_macosx_rpath#variable:CMAKE_MACOSX_RPATH "CMAKE_MACOSX_RPATH") if it is set when a target is created.
Runtime paths will also be embedded in binaries using this target and can be controlled by the [`INSTALL_RPATH`](install_rpath#prop_tgt:INSTALL_RPATH "INSTALL_RPATH") target property on the target linking to this target.
Policy [`CMP0042`](../policy/cmp0042#policy:CMP0042 "CMP0042") was introduced to change the default value of `MACOSX_RPATH` to `TRUE`. This is because use of `@rpath` is a more flexible and powerful alternative to `@executable_path` and `@loader_path`.
cmake CXX_EXTENSIONS CXX\_EXTENSIONS
===============
Boolean specifying whether compiler specific extensions are requested.
This property specifies whether compiler specific extensions should be used. For some compilers, this results in adding a flag such as `-std=gnu++11` instead of `-std=c++11` to the compile line. This property is `ON` by default. The basic C++ standard level is controlled by the [`CXX_STANDARD`](cxx_standard#prop_tgt:CXX_STANDARD "CXX_STANDARD") target property.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
This property is initialized by the value of the [`CMAKE_CXX_EXTENSIONS`](../variable/cmake_cxx_extensions#variable:CMAKE_CXX_EXTENSIONS "CMAKE_CXX_EXTENSIONS") variable if it is set when a target is created.
cmake <LANG>_CLANG_TIDY <LANG>\_CLANG\_TIDY
===================
This property is implemented only when `<LANG>` is `C` or `CXX`.
Specify a [;-list](../manual/cmake-language.7#cmake-language-lists) containing a command line for the `clang-tidy` tool. The [Makefile Generators](../manual/cmake-generators.7#makefile-generators) and the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator will run this tool along with the compiler and report a warning if the tool reports any problems.
This property is initialized by the value of the [`CMAKE_<LANG>_CLANG_TIDY`](# "CMAKE_<LANG>_CLANG_TIDY") variable if it is set when a target is created.
cmake LINK_DEPENDS_NO_SHARED LINK\_DEPENDS\_NO\_SHARED
=========================
Do not depend on linked shared library files.
Set this property to true to tell CMake generators not to add file-level dependencies on the shared library files linked by this target. Modification to the shared libraries will not be sufficient to re-link this target. Logical target-level dependencies will not be affected so the linked shared libraries will still be brought up to date before this target is built.
This property is initialized by the value of the variable CMAKE\_LINK\_DEPENDS\_NO\_SHARED if it is set when a target is created.
cmake RUNTIME_OUTPUT_DIRECTORY_<CONFIG> RUNTIME\_OUTPUT\_DIRECTORY\_<CONFIG>
====================================
Per-configuration output directory for [RUNTIME](../manual/cmake-buildsystem.7#runtime-output-artifacts) target files.
This is a per-configuration version of the [`RUNTIME_OUTPUT_DIRECTORY`](runtime_output_directory#prop_tgt:RUNTIME_OUTPUT_DIRECTORY "RUNTIME_OUTPUT_DIRECTORY") target property, but multi-configuration generators (VS, Xcode) do NOT append a per-configuration subdirectory to the specified directory. This property is initialized by the value of the [`CMAKE_RUNTIME_OUTPUT_DIRECTORY_<CONFIG>`](# "CMAKE_RUNTIME_OUTPUT_DIRECTORY_<CONFIG>") variable if it is set when a target is created.
Contents of `RUNTIME_OUTPUT_DIRECTORY_<CONFIG>` may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)").
cmake BINARY_DIR BINARY\_DIR
===========
This read-only property reports the value of the [`CMAKE_CURRENT_BINARY_DIR`](../variable/cmake_current_binary_dir#variable:CMAKE_CURRENT_BINARY_DIR "CMAKE_CURRENT_BINARY_DIR") variable in the directory in which the target was defined.
cmake VS_GLOBAL_KEYWORD VS\_GLOBAL\_KEYWORD
===================
Visual Studio project keyword for VS 10 (2010) and newer.
Sets the “keyword” attribute for a generated Visual Studio project. Defaults to “Win32Proj”. You may wish to override this value with “ManagedCProj”, for example, in a Visual Studio managed C++ unit test project.
Use the [`VS_KEYWORD`](vs_keyword#prop_tgt:VS_KEYWORD "VS_KEYWORD") target property to set the keyword for Visual Studio 9 (2008) and older.
cmake INSTALL_RPATH INSTALL\_RPATH
==============
The rpath to use for installed targets.
A semicolon-separated list specifying the rpath to use in installed targets (for platforms that support it). This property is initialized by the value of the variable CMAKE\_INSTALL\_RPATH if it is set when a target is created.
cmake EchoString EchoString
==========
A message to be displayed when the target is built.
A message to display on some generators (such as makefiles) when the target is built.
cmake COMPILE_PDB_NAME COMPILE\_PDB\_NAME
==================
Output name for the MS debug symbol `.pdb` file generated by the compiler while building source files.
This property specifies the base name for the debug symbols file. If not set, the default is unspecified.
Note
The compiler-generated program database files are specified by the `/Fd` compiler flag and are not the same as linker-generated program database files specified by the `/pdb` linker flag. Use the [`PDB_NAME`](pdb_name#prop_tgt:PDB_NAME "PDB_NAME") property to specify the latter.
cmake VS_SCC_LOCALPATH VS\_SCC\_LOCALPATH
==================
Visual Studio Source Code Control Local Path.
Can be set to change the visual studio source code control local path property.
cmake PDB_OUTPUT_DIRECTORY_<CONFIG> PDB\_OUTPUT\_DIRECTORY\_<CONFIG>
================================
Per-configuration output directory for the MS debug symbol `.pdb` file generated by the linker for an executable or shared library target.
This is a per-configuration version of [`PDB_OUTPUT_DIRECTORY`](pdb_output_directory#prop_tgt:PDB_OUTPUT_DIRECTORY "PDB_OUTPUT_DIRECTORY"), but multi-configuration generators (VS, Xcode) do NOT append a per-configuration subdirectory to the specified directory. This property is initialized by the value of the [`CMAKE_PDB_OUTPUT_DIRECTORY_<CONFIG>`](# "CMAKE_PDB_OUTPUT_DIRECTORY_<CONFIG>") variable if it is set when a target is created.
Note
This property does not apply to STATIC library targets because no linker is invoked to produce them so they have no linker-generated `.pdb` file containing debug symbols.
The linker-generated program database files are specified by the `/pdb` linker flag and are not the same as compiler-generated program database files specified by the `/Fd` compiler flag. Use the [`COMPILE_PDB_OUTPUT_DIRECTORY_<CONFIG>`](# "COMPILE_PDB_OUTPUT_DIRECTORY_<CONFIG>") property to specify the latter.
cmake VS_WINRT_COMPONENT VS\_WINRT\_COMPONENT
====================
Mark a target as a Windows Runtime component for the Visual Studio generator. Compile the target with `C++/CX` language extensions for Windows Runtime. For `SHARED` and `MODULE` libraries, this also defines the `_WINRT_DLL` preprocessor macro.
Note
Currently this is implemented only by Visual Studio generators. Support may be added to other generators in the future.
cmake EXPORT_NAME EXPORT\_NAME
============
Exported name for target files.
This sets the name for the IMPORTED target generated when it this target is is exported. If not set, the logical target name is used by default.
cmake VS_MOBILE_EXTENSIONS_VERSION VS\_MOBILE\_EXTENSIONS\_VERSION
===============================
Visual Studio Windows 10 Mobile Extensions Version
Specifies the version of the Mobile Extensions that should be included in the target. For example `10.0.10240.0`. If the value is not specified, the Mobile Extensions will not be included. To use the same version of the extensions as the Windows 10 SDK that is being used, you can use the [`CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION`](../variable/cmake_vs_windows_target_platform_version#variable:CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION "CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION") variable.
| programming_docs |
cmake INTERFACE_COMPILE_OPTIONS INTERFACE\_COMPILE\_OPTIONS
===========================
List of public compile options requirements for a library.
Targets may populate this property to publish the compile options required to compile against the headers for the target. The [`target_compile_options()`](../command/target_compile_options#command:target_compile_options "target_compile_options") command populates this property with values given to the `PUBLIC` and `INTERFACE` keywords. Projects may also get and set the property directly.
When target dependencies are specified using [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries"), CMake will read this property from all target dependencies to determine the build properties of the consumer.
Contents of `INTERFACE_COMPILE_OPTIONS` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") -manual for more on defining buildsystem properties.
cmake MANUALLY_ADDED_DEPENDENCIES MANUALLY\_ADDED\_DEPENDENCIES
=============================
Get manually added dependencies to other top-level targets.
This read-only property can be used to query all dependencies that were added for this target with the [`add_dependencies()`](../command/add_dependencies#command:add_dependencies "add_dependencies") command.
cmake OUTPUT_NAME_<CONFIG> OUTPUT\_NAME\_<CONFIG>
======================
Per-configuration target file base name.
This is the configuration-specific version of the [`OUTPUT_NAME`](output_name#prop_tgt:OUTPUT_NAME "OUTPUT_NAME") target property.
cmake SOVERSION SOVERSION
=========
What version number is this target.
For shared libraries [`VERSION`](version#prop_tgt:VERSION "VERSION") and `SOVERSION` can be used to specify the build version and API version respectively. When building or installing appropriate symlinks are created if the platform supports symlinks and the linker supports so-names. If only one of both is specified the missing is assumed to have the same version number. `SOVERSION` is ignored if [`NO_SONAME`](no_soname#prop_tgt:NO_SONAME "NO_SONAME") property is set.
Windows Versions
----------------
For shared libraries and executables on Windows the [`VERSION`](version#prop_tgt:VERSION "VERSION") attribute is parsed to extract a `<major>.<minor>` version number. These numbers are used as the image version of the binary.
Mach-O Versions
---------------
For shared libraries and executables on Mach-O systems (e.g. OS X, iOS), the `SOVERSION` property corresponds to *compatibility version* and [`VERSION`](version#prop_tgt:VERSION "VERSION") to *current version*. See the [`FRAMEWORK`](framework#prop_tgt:FRAMEWORK "FRAMEWORK") target property for an example. Versions of Mach-O binaries may be checked with the `otool -L <binary>` command.
cmake IMPORTED_SONAME_<CONFIG> IMPORTED\_SONAME\_<CONFIG>
==========================
<CONFIG>-specific version of IMPORTED\_SONAME property.
Configuration names correspond to those provided by the project from which the target is imported.
cmake DEBUG_POSTFIX DEBUG\_POSTFIX
==============
See target property <CONFIG>\_POSTFIX.
This property is a special case of the more-general <CONFIG>\_POSTFIX property for the DEBUG configuration.
cmake CUDA_EXTENSIONS CUDA\_EXTENSIONS
================
Boolean specifying whether compiler specific extensions are requested.
This property specifies whether compiler specific extensions should be used. For some compilers, this results in adding a flag such as `-std=gnu++11` instead of `-std=c++11` to the compile line. This property is `ON` by default. The basic CUDA/C++ standard level is controlled by the [`CUDA_STANDARD`](cuda_standard#prop_tgt:CUDA_STANDARD "CUDA_STANDARD") target property.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
This property is initialized by the value of the [`CMAKE_CUDA_EXTENSIONS`](../variable/cmake_cuda_extensions#variable:CMAKE_CUDA_EXTENSIONS "CMAKE_CUDA_EXTENSIONS") variable if it is set when a target is created.
cmake EXCLUDE_FROM_DEFAULT_BUILD EXCLUDE\_FROM\_DEFAULT\_BUILD
=============================
Exclude target from “Build Solution”.
This property is only used by Visual Studio generators. When set to TRUE, the target will not be built when you press “Build Solution”.
cmake LINK_INTERFACE_LIBRARIES LINK\_INTERFACE\_LIBRARIES
==========================
List public interface libraries for a shared library or executable.
By default linking to a shared library target transitively links to targets with which the library itself was linked. For an executable with exports (see the [`ENABLE_EXPORTS`](enable_exports#prop_tgt:ENABLE_EXPORTS "ENABLE_EXPORTS") target property) no default transitive link dependencies are used. This property replaces the default transitive link dependencies with an explicit list. When the target is linked into another target using the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command, the libraries listed (and recursively their link interface libraries) will be provided to the other target also. If the list is empty then no transitive link dependencies will be incorporated when this target is linked into another target even if the default set is non-empty. This property is initialized by the value of the [`CMAKE_LINK_INTERFACE_LIBRARIES`](../variable/cmake_link_interface_libraries#variable:CMAKE_LINK_INTERFACE_LIBRARIES "CMAKE_LINK_INTERFACE_LIBRARIES") variable if it is set when a target is created. This property is ignored for `STATIC` libraries.
This property is overridden by the [`INTERFACE_LINK_LIBRARIES`](interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES") property if policy [`CMP0022`](../policy/cmp0022#policy:CMP0022 "CMP0022") is `NEW`.
This property is deprecated. Use [`INTERFACE_LINK_LIBRARIES`](interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES") instead.
Creating Relocatable Packages
-----------------------------
Note that it is not advisable to populate the `LINK_INTERFACE_LIBRARIES` of a target with absolute paths to dependencies. That would hard-code into installed packages the library file paths for dependencies **as found on the machine the package was made on**.
See the [Creating Relocatable Packages](../manual/cmake-packages.7#creating-relocatable-packages) section of the [`cmake-packages(7)`](../manual/cmake-packages.7#manual:cmake-packages(7) "cmake-packages(7)") manual for discussion of additional care that must be taken when specifying usage requirements while creating packages for redistribution.
cmake COMPILE_OPTIONS COMPILE\_OPTIONS
================
List of options to pass to the compiler.
This property holds a [;-list](../manual/cmake-language.7#cmake-language-lists) of options specified so far for its target. Use the [`target_compile_options()`](../command/target_compile_options#command:target_compile_options "target_compile_options") command to append more options.
This property is initialized by the [`COMPILE_OPTIONS`](../prop_dir/compile_options#prop_dir:COMPILE_OPTIONS "COMPILE_OPTIONS") directory property when a target is created, and is used by the generators to set the options for the compiler.
Contents of `COMPILE_OPTIONS` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake LINK_SEARCH_START_STATIC LINK\_SEARCH\_START\_STATIC
===========================
Assume the linker looks for static libraries by default.
Some linkers support switches such as -Bstatic and -Bdynamic to determine whether to use static or shared libraries for -lXXX options. CMake uses these options to set the link type for libraries whose full paths are not known or (in some cases) are in implicit link directories for the platform. By default the linker search type is assumed to be -Bdynamic at the beginning of the library list. This property switches the assumption to -Bstatic. It is intended for use when linking an executable statically (e.g. with the GNU -static option).
This property is initialized by the value of the variable CMAKE\_LINK\_SEARCH\_START\_STATIC if it is set when a target is created.
See also LINK\_SEARCH\_END\_STATIC.
cmake SUFFIX SUFFIX
======
What comes after the target name.
A target property that can be set to override the suffix (such as “.so” or “.exe”) on the name of a library, module or executable.
cmake INTERPROCEDURAL_OPTIMIZATION_<CONFIG> INTERPROCEDURAL\_OPTIMIZATION\_<CONFIG>
=======================================
Per-configuration interprocedural optimization for a target.
This is a per-configuration version of INTERPROCEDURAL\_OPTIMIZATION. If set, this property overrides the generic property for the named configuration.
This property is initialized by the [`CMAKE_INTERPROCEDURAL_OPTIMIZATION_<CONFIG>`](# "CMAKE_INTERPROCEDURAL_OPTIMIZATION_<CONFIG>") variable if it is set when a target is created.
cmake <CONFIG>_POSTFIX <CONFIG>\_POSTFIX
=================
Postfix to append to the target file name for configuration <CONFIG>.
When building with configuration <CONFIG> the value of this property is appended to the target file name built on disk. For non-executable targets, this property is initialized by the value of the variable CMAKE\_<CONFIG>\_POSTFIX if it is set when a target is created. This property is ignored on the Mac for Frameworks and App Bundles.
cmake BUNDLE_EXTENSION BUNDLE\_EXTENSION
=================
The file extension used to name a [`BUNDLE`](bundle#prop_tgt:BUNDLE "BUNDLE"), a [`FRAMEWORK`](framework#prop_tgt:FRAMEWORK "FRAMEWORK"), or a [`MACOSX_BUNDLE`](macosx_bundle#prop_tgt:MACOSX_BUNDLE "MACOSX_BUNDLE") target on the OS X and iOS.
The default value is `bundle`, `framework`, or `app` for the respective target types.
cmake LIBRARY_OUTPUT_NAME_<CONFIG> LIBRARY\_OUTPUT\_NAME\_<CONFIG>
===============================
Per-configuration output name for [LIBRARY](../manual/cmake-buildsystem.7#library-output-artifacts) target files.
This is the configuration-specific version of the [`LIBRARY_OUTPUT_NAME`](library_output_name#prop_tgt:LIBRARY_OUTPUT_NAME "LIBRARY_OUTPUT_NAME") target property.
cmake LINK_DEPENDS LINK\_DEPENDS
=============
Additional files on which a target binary depends for linking.
Specifies a semicolon-separated list of full-paths to files on which the link rule for this target depends. The target binary will be linked if any of the named files is newer than it.
This property is ignored by non-Makefile generators. It is intended to specify dependencies on “linker scripts” for custom Makefile link rules.
cmake VERSION VERSION
=======
What version number is this target.
For shared libraries `VERSION` and [`SOVERSION`](soversion#prop_tgt:SOVERSION "SOVERSION") can be used to specify the build version and API version respectively. When building or installing appropriate symlinks are created if the platform supports symlinks and the linker supports so-names. If only one of both is specified the missing is assumed to have the same version number. For executables `VERSION` can be used to specify the build version. When building or installing appropriate symlinks are created if the platform supports symlinks.
Windows Versions
----------------
For shared libraries and executables on Windows the `VERSION` attribute is parsed to extract a `<major>.<minor>` version number. These numbers are used as the image version of the binary.
Mach-O Versions
---------------
For shared libraries and executables on Mach-O systems (e.g. OS X, iOS), the [`SOVERSION`](soversion#prop_tgt:SOVERSION "SOVERSION") property correspond to *compatibility version* and `VERSION` to *current version*. See the [`FRAMEWORK`](framework#prop_tgt:FRAMEWORK "FRAMEWORK") target property for an example. Versions of Mach-O binaries may be checked with the `otool -L <binary>` command.
cmake IMPORTED IMPORTED
========
Read-only indication of whether a target is IMPORTED.
The boolean value of this property is `True` for targets created with the IMPORTED option to [`add_executable()`](../command/add_executable#command:add_executable "add_executable") or [`add_library()`](../command/add_library#command:add_library "add_library"). It is `False` for targets built within the project.
cmake Fortran_FORMAT Fortran\_FORMAT
===============
Set to FIXED or FREE to indicate the Fortran source layout.
This property tells CMake whether the Fortran source files in a target use fixed-format or free-format. CMake will pass the corresponding format flag to the compiler. Use the source-specific Fortran\_FORMAT property to change the format of a specific source file. If the variable CMAKE\_Fortran\_FORMAT is set when a target is created its value is used to initialize this property.
cmake C_STANDARD C\_STANDARD
===========
The C standard whose features are requested to build this target.
This property specifies the C standard whose features are requested to build this target. For some compilers, this results in adding a flag such as `-std=gnu11` to the compile line. For compilers that have no notion of a standard level, such as MSVC, this has no effect.
Supported values are `90`, `99` and `11`.
If the value requested does not result in a compile flag being added for the compiler in use, a previous standard flag will be added instead. This means that using:
```
set_property(TARGET tgt PROPERTY C_STANDARD 11)
```
with a compiler which does not support `-std=gnu11` or an equivalent flag will not result in an error or warning, but will instead add the `-std=gnu99` or `-std=gnu90` flag if supported. This “decay” behavior may be controlled with the [`C_STANDARD_REQUIRED`](c_standard_required#prop_tgt:C_STANDARD_REQUIRED "C_STANDARD_REQUIRED") target property. Additionally, the [`C_EXTENSIONS`](c_extensions#prop_tgt:C_EXTENSIONS "C_EXTENSIONS") target property may be used to control whether compiler-specific extensions are enabled on a per-target basis.
See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
This property is initialized by the value of the [`CMAKE_C_STANDARD`](../variable/cmake_c_standard#variable:CMAKE_C_STANDARD "CMAKE_C_STANDARD") variable if it is set when a target is created.
cmake BUILD_WITH_INSTALL_NAME_DIR BUILD\_WITH\_INSTALL\_NAME\_DIR
===============================
`BUILD_WITH_INSTALL_NAME_DIR` is a boolean specifying whether the macOS `install_name` of a target in the build tree uses the directory given by [`INSTALL_NAME_DIR`](install_name_dir#prop_tgt:INSTALL_NAME_DIR "INSTALL_NAME_DIR"). This setting only applies to targets on macOS.
This property is initialized by the value of the variable [`CMAKE_BUILD_WITH_INSTALL_NAME_DIR`](../variable/cmake_build_with_install_name_dir#variable:CMAKE_BUILD_WITH_INSTALL_NAME_DIR "CMAKE_BUILD_WITH_INSTALL_NAME_DIR") if it is set when a target is created.
If this property is not set and policy [`CMP0068`](../policy/cmp0068#policy:CMP0068 "CMP0068") is not `NEW`, the value of [`BUILD_WITH_INSTALL_RPATH`](build_with_install_rpath#prop_tgt:BUILD_WITH_INSTALL_RPATH "BUILD_WITH_INSTALL_RPATH") is used in its place.
cmake LABELS LABELS
======
Specify a list of text labels associated with a target.
Target label semantics are currently unspecified.
cmake FRAMEWORK_VERSION FRAMEWORK\_VERSION
==================
Version of a framework created using the [`FRAMEWORK`](framework#prop_tgt:FRAMEWORK "FRAMEWORK") target property (e.g. `A`).
This property only affects OS X, as iOS doesn’t have versioned directory structure.
cmake IMPORTED_IMPLIB IMPORTED\_IMPLIB
================
Full path to the import library for an IMPORTED target.
Set this to the location of the “.lib” part of a windows DLL. Ignored for non-imported targets.
cmake RULE_LAUNCH_CUSTOM RULE\_LAUNCH\_CUSTOM
====================
Specify a launcher for custom rules.
See the global property of the same name for details. This overrides the global and directory property for a target.
cmake FOLDER FOLDER
======
Set the folder name. Use to organize targets in an IDE.
Targets with no FOLDER property will appear as top level entities in IDEs like Visual Studio. Targets with the same FOLDER property value will appear next to each other in a folder of that name. To nest folders, use FOLDER values such as ‘GUI/Dialogs’ with ‘/’ characters separating folder levels.
cmake VS_DOTNET_REFERENCES_COPY_LOCAL VS\_DOTNET\_REFERENCES\_COPY\_LOCAL
===================================
Sets the **Copy Local** property for all .NET hint references in the target
Boolean property to enable/disable copying of .NET hint references to output directory. The default is `ON`.
cmake VS_WINRT_EXTENSIONS VS\_WINRT\_EXTENSIONS
=====================
Deprecated. Use [`VS_WINRT_COMPONENT`](vs_winrt_component#prop_tgt:VS_WINRT_COMPONENT "VS_WINRT_COMPONENT") instead. This property was an experimental partial implementation of that one.
cmake ECLIPSE_EXTRA_NATURES ECLIPSE\_EXTRA\_NATURES
=======================
List of natures to add to the generated Eclipse project file.
Eclipse projects specify language plugins by using natures. This property should be set to the unique identifier for a nature (which looks like a Java package name).
cmake CMAKE_CXX_KNOWN_FEATURES CMAKE\_CXX\_KNOWN\_FEATURES
===========================
List of C++ features known to this version of CMake.
The features listed in this global property may be known to be available to the C++ compiler. If the feature is available with the C++ compiler, it will be listed in the [`CMAKE_CXX_COMPILE_FEATURES`](../variable/cmake_cxx_compile_features#variable:CMAKE_CXX_COMPILE_FEATURES "CMAKE_CXX_COMPILE_FEATURES") variable.
The features listed here may be used with the [`target_compile_features()`](../command/target_compile_features#command:target_compile_features "target_compile_features") command. See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
The features known to this version of CMake are:
`cxx_std_98` Compiler mode is aware of C++ 98.
`cxx_std_11` Compiler mode is aware of C++ 11.
`cxx_std_14` Compiler mode is aware of C++ 14.
`cxx_std_17` Compiler mode is aware of C++ 17.
`cxx_aggregate_default_initializers` Aggregate default initializers, as defined in [N3605](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3605.html).
`cxx_alias_templates` Template aliases, as defined in [N2258](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2258.pdf).
`cxx_alignas` Alignment control `alignas`, as defined in [N2341](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2341.pdf).
`cxx_alignof` Alignment control `alignof`, as defined in [N2341](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2341.pdf).
`cxx_attributes` Generic attributes, as defined in [N2761](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2761.pdf).
`cxx_attribute_deprecated`
`[[deprecated]]` attribute, as defined in [N3760](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3760.html).
`cxx_auto_type` Automatic type deduction, as defined in [N1984](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1984.pdf).
`cxx_binary_literals` Binary literals, as defined in [N3472](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3472.pdf).
`cxx_constexpr` Constant expressions, as defined in [N2235](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2235.pdf).
`cxx_contextual_conversions` Contextual conversions, as defined in [N3323](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3323.pdf).
`cxx_decltype_incomplete_return_types` Decltype on incomplete return types, as defined in [N3276](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3276.pdf).
`cxx_decltype` Decltype, as defined in [N2343](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2343.pdf).
`cxx_decltype_auto`
`decltype(auto)` semantics, as defined in [N3638](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3638.html).
`cxx_default_function_template_args` Default template arguments for function templates, as defined in [DR226](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#226)
`cxx_defaulted_functions` Defaulted functions, as defined in [N2346](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2346.htm).
`cxx_defaulted_move_initializers` Defaulted move initializers, as defined in [N3053](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3053.html).
`cxx_delegating_constructors` Delegating constructors, as defined in [N1986](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1986.pdf).
`cxx_deleted_functions` Deleted functions, as defined in [N2346](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2346.htm).
`cxx_digit_separators` Digit separators, as defined in [N3781](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3781.pdf).
`cxx_enum_forward_declarations` Enum forward declarations, as defined in [N2764](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2764.pdf).
`cxx_explicit_conversions` Explicit conversion operators, as defined in [N2437](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2437.pdf).
`cxx_extended_friend_declarations` Extended friend declarations, as defined in [N1791](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1791.pdf).
`cxx_extern_templates` Extern templates, as defined in [N1987](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1987.htm).
`cxx_final` Override control `final` keyword, as defined in [N2928](http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2009/n2928.htm), [N3206](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3206.htm) and [N3272](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3272.htm).
`cxx_func_identifier` Predefined `__func__` identifier, as defined in [N2340](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2340.htm).
`cxx_generalized_initializers` Initializer lists, as defined in [N2672](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2672.htm).
`cxx_generic_lambdas` Generic lambdas, as defined in [N3649](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3649.html).
`cxx_inheriting_constructors` Inheriting constructors, as defined in [N2540](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2540.htm).
`cxx_inline_namespaces` Inline namespaces, as defined in [N2535](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2535.htm).
`cxx_lambdas` Lambda functions, as defined in [N2927](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2927.pdf).
`cxx_lambda_init_captures` Initialized lambda captures, as defined in [N3648](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3648.html).
`cxx_local_type_template_args` Local and unnamed types as template arguments, as defined in [N2657](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2657.htm).
`cxx_long_long_type`
`long long` type, as defined in [N1811](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1811.pdf).
`cxx_noexcept` Exception specifications, as defined in [N3050](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3050.html).
`cxx_nonstatic_member_init` Non-static data member initialization, as defined in [N2756](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2756.htm).
`cxx_nullptr` Null pointer, as defined in [N2431](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2431.pdf).
`cxx_override` Override control `override` keyword, as defined in [N2928](http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2009/n2928.htm), [N3206](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3206.htm) and [N3272](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3272.htm).
`cxx_range_for` Range-based for, as defined in [N2930](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2930.html).
`cxx_raw_string_literals` Raw string literals, as defined in [N2442](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2442.htm).
`cxx_reference_qualified_functions` Reference qualified functions, as defined in [N2439](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2439.htm).
`cxx_relaxed_constexpr` Relaxed constexpr, as defined in [N3652](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3652.html).
`cxx_return_type_deduction` Return type deduction on normal functions, as defined in [N3386](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3386.html).
`cxx_right_angle_brackets` Right angle bracket parsing, as defined in [N1757](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1757.html).
`cxx_rvalue_references` R-value references, as defined in [N2118](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2118.html).
`cxx_sizeof_member` Size of non-static data members, as defined in [N2253](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2253.html).
`cxx_static_assert` Static assert, as defined in [N1720](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1720.html).
`cxx_strong_enums` Strongly typed enums, as defined in [N2347](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2347.pdf).
`cxx_thread_local` Thread-local variables, as defined in [N2659](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2659.htm).
`cxx_trailing_return_types` Automatic function return type, as defined in [N2541](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2541.htm).
`cxx_unicode_literals` Unicode string literals, as defined in [N2442](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2442.htm).
`cxx_uniform_initialization` Uniform initialization, as defined in [N2640](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2640.pdf).
`cxx_unrestricted_unions` Unrestricted unions, as defined in [N2544](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2544.pdf).
`cxx_user_literals` User-defined literals, as defined in [N2765](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2765.pdf).
`cxx_variable_templates` Variable templates, as defined in [N3651](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3651.pdf).
`cxx_variadic_macros` Variadic macros, as defined in [N1653](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1653.htm).
`cxx_variadic_templates` Variadic templates, as defined in [N2242](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2242.pdf).
`cxx_template_template_parameters` Template template parameters, as defined in `ISO/IEC 14882:1998`.
| programming_docs |
cmake AUTORCC_SOURCE_GROUP AUTORCC\_SOURCE\_GROUP
======================
Name of the [`source_group()`](../command/source_group#command:source_group "source_group") for [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC") generated files.
When set this is used instead of [`AUTOGEN_SOURCE_GROUP`](autogen_source_group#prop_gbl:AUTOGEN_SOURCE_GROUP "AUTOGEN_SOURCE_GROUP") for files generated by [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC").
cmake AUTOGEN_TARGETS_FOLDER AUTOGEN\_TARGETS\_FOLDER
========================
Name of [`FOLDER`](../prop_tgt/folder#prop_tgt:FOLDER "FOLDER") for `*_autogen` targets that are added automatically by CMake for targets for which [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") is enabled.
If not set, CMake uses the [`FOLDER`](../prop_tgt/folder#prop_tgt:FOLDER "FOLDER") property of the parent target as a default value for this property. See also the documentation for the [`FOLDER`](../prop_tgt/folder#prop_tgt:FOLDER "FOLDER") target property and the [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") target property.
cmake ENABLED_FEATURES ENABLED\_FEATURES
=================
List of features which are enabled during the CMake run.
List of features which are enabled during the CMake run. By default it contains the names of all packages which were found. This is determined using the <NAME>\_FOUND variables. Packages which are searched QUIET are not listed. A project can add its own features to this list. This property is used by the macros in FeatureSummary.cmake.
cmake GLOBAL_DEPENDS_DEBUG_MODE GLOBAL\_DEPENDS\_DEBUG\_MODE
============================
Enable global target dependency graph debug mode.
CMake automatically analyzes the global inter-target dependency graph at the beginning of native build system generation. This property causes it to display details of its analysis to stderr.
cmake USE_FOLDERS USE\_FOLDERS
============
Use the [`FOLDER`](../prop_tgt/folder#prop_tgt:FOLDER "FOLDER") target property to organize targets into folders.
If not set, CMake treats this property as OFF by default. CMake generators that are capable of organizing into a hierarchy of folders use the values of the [`FOLDER`](../prop_tgt/folder#prop_tgt:FOLDER "FOLDER") target property to name those folders. See also the documentation for the FOLDER target property.
cmake PREDEFINED_TARGETS_FOLDER PREDEFINED\_TARGETS\_FOLDER
===========================
Name of FOLDER for targets that are added automatically by CMake.
If not set, CMake uses “CMakePredefinedTargets” as a default value for this property. Targets such as INSTALL, PACKAGE and RUN\_TESTS will be organized into this FOLDER. See also the documentation for the [`FOLDER`](../prop_tgt/folder#prop_tgt:FOLDER "FOLDER") target property.
cmake AUTOMOC_TARGETS_FOLDER AUTOMOC\_TARGETS\_FOLDER
========================
Name of [`FOLDER`](../prop_tgt/folder#prop_tgt:FOLDER "FOLDER") for `*_autogen` targets that are added automatically by CMake for targets for which [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") is enabled.
This property is obsolete. Use [`AUTOGEN_TARGETS_FOLDER`](autogen_targets_folder#prop_gbl:AUTOGEN_TARGETS_FOLDER "AUTOGEN_TARGETS_FOLDER") instead.
If not set, CMake uses the [`FOLDER`](../prop_tgt/folder#prop_tgt:FOLDER "FOLDER") property of the parent target as a default value for this property. See also the documentation for the [`FOLDER`](../prop_tgt/folder#prop_tgt:FOLDER "FOLDER") target property and the [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") target property.
cmake FIND_LIBRARY_USE_LIBX32_PATHS FIND\_LIBRARY\_USE\_LIBX32\_PATHS
=================================
Whether the [`find_library()`](../command/find_library#command:find_library "find_library") command should automatically search `libx32` directories.
`FIND_LIBRARY_USE_LIBX32_PATHS` is a boolean specifying whether the [`find_library()`](../command/find_library#command:find_library "find_library") command should automatically search the `libx32` variant of directories called `lib` in the search path when building x32-abi binaries.
See also the [`CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX`](../variable/cmake_find_library_custom_lib_suffix#variable:CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX "CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX") variable.
cmake PACKAGES_NOT_FOUND PACKAGES\_NOT\_FOUND
====================
List of packages which were not found during the CMake run.
List of packages which were not found during the CMake run. Whether a package has been found is determined using the <NAME>\_FOUND variables.
cmake FIND_LIBRARY_USE_LIB64_PATHS FIND\_LIBRARY\_USE\_LIB64\_PATHS
================================
Whether [`find_library()`](../command/find_library#command:find_library "find_library") should automatically search lib64 directories.
FIND\_LIBRARY\_USE\_LIB64\_PATHS is a boolean specifying whether the [`find_library()`](../command/find_library#command:find_library "find_library") command should automatically search the lib64 variant of directories called lib in the search path when building 64-bit binaries.
See also the [`CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX`](../variable/cmake_find_library_custom_lib_suffix#variable:CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX "CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX") variable.
cmake ENABLED_LANGUAGES ENABLED\_LANGUAGES
==================
Read-only property that contains the list of currently enabled languages
Set to list of currently enabled languages.
cmake RULE_LAUNCH_COMPILE RULE\_LAUNCH\_COMPILE
=====================
Specify a launcher for compile rules.
[Makefile Generators](../manual/cmake-generators.7#makefile-generators) and the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator prefix compiler commands with the given launcher command line. This is intended to allow launchers to intercept build problems with high granularity. Other generators ignore this property because their underlying build systems provide no hook to wrap individual commands with a launcher.
cmake XCODE_EMIT_EFFECTIVE_PLATFORM_NAME XCODE\_EMIT\_EFFECTIVE\_PLATFORM\_NAME
======================================
Control emission of `EFFECTIVE_PLATFORM_NAME` by the Xcode generator.
It is required for building the same target with multiple SDKs. A common use case is the parallel use of `iphoneos` and `iphonesimulator` SDKs.
Three different states possible that control when the Xcode generator emits the `EFFECTIVE_PLATFORM_NAME` variable:
* If set to `ON` it will always be emitted
* If set to `OFF` it will never be emitted
* If unset (the default) it will only be emitted when the project was configured for an embedded Xcode SDK like iOS, tvOS, watchOS or any of the simulators.
Note
When this behavior is enable for generated Xcode projects, the `EFFECTIVE_PLATFORM_NAME` variable will leak into [`Generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") like `TARGET_FILE` and will render those mostly unusable.
cmake TARGET_SUPPORTS_SHARED_LIBS TARGET\_SUPPORTS\_SHARED\_LIBS
==============================
Does the target platform support shared libraries.
TARGET\_SUPPORTS\_SHARED\_LIBS is a boolean specifying whether the target platform supports shared libraries. Basically all current general general purpose OS do so, the exception are usually embedded systems with no or special OSs.
cmake AUTOGEN_SOURCE_GROUP AUTOGEN\_SOURCE\_GROUP
======================
Name of the [`source_group()`](../command/source_group#command:source_group "source_group") for [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") and [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC") generated files.
Files generated by [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") and [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC") are not always known at configure time and therefore can’t be passed to [`source_group()`](../command/source_group#command:source_group "source_group"). [`AUTOGEN_SOURCE_GROUP`](#prop_gbl:AUTOGEN_SOURCE_GROUP "AUTOGEN_SOURCE_GROUP") an be used instead to generate or select a source group for [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") and [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC") generated files.
For [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") and [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC") specific overrides see [`AUTOMOC_SOURCE_GROUP`](automoc_source_group#prop_gbl:AUTOMOC_SOURCE_GROUP "AUTOMOC_SOURCE_GROUP") and [`AUTORCC_SOURCE_GROUP`](autorcc_source_group#prop_gbl:AUTORCC_SOURCE_GROUP "AUTORCC_SOURCE_GROUP") respectively.
cmake RULE_MESSAGES RULE\_MESSAGES
==============
Specify whether to report a message for each make rule.
This property specifies whether Makefile generators should add a progress message describing what each build rule does. If the property is not set the default is ON. Set the property to OFF to disable granular messages and report only as each target completes. This is intended to allow scripted builds to avoid the build time cost of detailed reports. If a `CMAKE_RULE_MESSAGES` cache entry exists its value initializes the value of this property. Non-Makefile generators currently ignore this property.
cmake ALLOW_DUPLICATE_CUSTOM_TARGETS ALLOW\_DUPLICATE\_CUSTOM\_TARGETS
=================================
Allow duplicate custom targets to be created.
Normally CMake requires that all targets built in a project have globally unique logical names (see policy CMP0002). This is necessary to generate meaningful project file names in Xcode and VS IDE generators. It also allows the target names to be referenced unambiguously.
Makefile generators are capable of supporting duplicate custom target names. For projects that care only about Makefile generators and do not wish to support Xcode or VS IDE generators, one may set this property to true to allow duplicate custom targets. The property allows multiple add\_custom\_target command calls in different directories to specify the same target name. However, setting this property will cause non-Makefile generators to produce an error and refuse to generate the project.
cmake CMAKE_C_KNOWN_FEATURES CMAKE\_C\_KNOWN\_FEATURES
=========================
List of C features known to this version of CMake.
The features listed in this global property may be known to be available to the C compiler. If the feature is available with the C compiler, it will be listed in the [`CMAKE_C_COMPILE_FEATURES`](../variable/cmake_c_compile_features#variable:CMAKE_C_COMPILE_FEATURES "CMAKE_C_COMPILE_FEATURES") variable.
The features listed here may be used with the [`target_compile_features()`](../command/target_compile_features#command:target_compile_features "target_compile_features") command. See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
The features known to this version of CMake are:
`c_std_90` Compiler mode is aware of C 90.
`c_std_99` Compiler mode is aware of C 99.
`c_std_11` Compiler mode is aware of C 11.
`c_function_prototypes` Function prototypes, as defined in `ISO/IEC 9899:1990`.
`c_restrict`
`restrict` keyword, as defined in `ISO/IEC 9899:1999`.
`c_static_assert` Static assert, as defined in `ISO/IEC 9899:2011`.
`c_variadic_macros` Variadic macros, as defined in `ISO/IEC 9899:1999`.
cmake AUTOMOC_SOURCE_GROUP AUTOMOC\_SOURCE\_GROUP
======================
Name of the [`source_group()`](../command/source_group#command:source_group "source_group") for [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") generated files.
When set this is used instead of [`AUTOGEN_SOURCE_GROUP`](autogen_source_group#prop_gbl:AUTOGEN_SOURCE_GROUP "AUTOGEN_SOURCE_GROUP") for files generated by [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC").
cmake TARGET_ARCHIVES_MAY_BE_SHARED_LIBS TARGET\_ARCHIVES\_MAY\_BE\_SHARED\_LIBS
=======================================
Set if shared libraries may be named like archives.
On AIX shared libraries may be named “lib<name>.a”. This property is set to true on such platforms.
cmake REPORT_UNDEFINED_PROPERTIES REPORT\_UNDEFINED\_PROPERTIES
=============================
If set, report any undefined properties to this file.
If this property is set to a filename then when CMake runs it will report any properties or variables that were accessed but not defined into the filename specified in this property.
cmake RULE_LAUNCH_LINK RULE\_LAUNCH\_LINK
==================
Specify a launcher for link rules.
[Makefile Generators](../manual/cmake-generators.7#makefile-generators) and the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator prefix link and archive commands with the given launcher command line. This is intended to allow launchers to intercept build problems with high granularity. Other generators ignore this property because their underlying build systems provide no hook to wrap individual commands with a launcher.
cmake PACKAGES_FOUND PACKAGES\_FOUND
===============
List of packages which were found during the CMake run.
List of packages which were found during the CMake run. Whether a package has been found is determined using the <NAME>\_FOUND variables.
cmake FIND_LIBRARY_USE_LIB32_PATHS FIND\_LIBRARY\_USE\_LIB32\_PATHS
================================
Whether the [`find_library()`](../command/find_library#command:find_library "find_library") command should automatically search `lib32` directories.
`FIND_LIBRARY_USE_LIB32_PATHS` is a boolean specifying whether the [`find_library()`](../command/find_library#command:find_library "find_library") command should automatically search the `lib32` variant of directories called `lib` in the search path when building 32-bit binaries.
See also the [`CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX`](../variable/cmake_find_library_custom_lib_suffix#variable:CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX "CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX") variable.
cmake GLOBAL_DEPENDS_NO_CYCLES GLOBAL\_DEPENDS\_NO\_CYCLES
===========================
Disallow global target dependency graph cycles.
CMake automatically analyzes the global inter-target dependency graph at the beginning of native build system generation. It reports an error if the dependency graph contains a cycle that does not consist of all STATIC library targets. This property tells CMake to disallow all cycles completely, even among static libraries.
cmake TARGET_MESSAGES TARGET\_MESSAGES
================
Specify whether to report the completion of each target.
This property specifies whether [Makefile Generators](../manual/cmake-generators.7#makefile-generators) should add a progress message describing that each target has been completed. If the property is not set the default is `ON`. Set the property to `OFF` to disable target completion messages.
This option is intended to reduce build output when little or no work needs to be done to bring the build tree up to date.
If a `CMAKE_TARGET_MESSAGES` cache entry exists its value initializes the value of this property.
Non-Makefile generators currently ignore this property.
See the counterpart property [`RULE_MESSAGES`](rule_messages#prop_gbl:RULE_MESSAGES "RULE_MESSAGES") to disable everything except for target completion messages.
cmake IN_TRY_COMPILE IN\_TRY\_COMPILE
================
Read-only property that is true during a try-compile configuration.
True when building a project inside a [`try_compile()`](../command/try_compile#command:try_compile "try_compile") or [`try_run()`](../command/try_run#command:try_run "try_run") command.
cmake DEBUG_CONFIGURATIONS DEBUG\_CONFIGURATIONS
=====================
Specify which configurations are for debugging.
The value must be a semi-colon separated list of configuration names. Currently this property is used only by the target\_link\_libraries command (see its documentation for details). Additional uses may be defined in the future.
This property must be set at the top level of the project and before the first target\_link\_libraries command invocation. If any entry in the list does not match a valid configuration for the project the behavior is undefined.
cmake GENERATOR_IS_MULTI_CONFIG GENERATOR\_IS\_MULTI\_CONFIG
============================
Read-only property that is true on multi-configuration generators.
True when using a multi-configuration generator (such as [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators) or [`Xcode`](https://cmake.org/cmake/help/v3.9/generator/Xcode.html#generator:Xcode "Xcode")). Multi-config generators use [`CMAKE_CONFIGURATION_TYPES`](../variable/cmake_configuration_types#variable:CMAKE_CONFIGURATION_TYPES "CMAKE_CONFIGURATION_TYPES") as the set of configurations and ignore [`CMAKE_BUILD_TYPE`](../variable/cmake_build_type#variable:CMAKE_BUILD_TYPE "CMAKE_BUILD_TYPE").
cmake RULE_LAUNCH_CUSTOM RULE\_LAUNCH\_CUSTOM
====================
Specify a launcher for custom rules.
[Makefile Generators](../manual/cmake-generators.7#makefile-generators) and the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator prefix custom commands with the given launcher command line. This is intended to allow launchers to intercept build problems with high granularity. Other generators ignore this property because their underlying build systems provide no hook to wrap individual commands with a launcher.
cmake DISABLED_FEATURES DISABLED\_FEATURES
==================
List of features which are disabled during the CMake run.
List of features which are disabled during the CMake run. By default it contains the names of all packages which were not found. This is determined using the <NAME>\_FOUND variables. Packages which are searched QUIET are not listed. A project can add its own features to this list. This property is used by the macros in FeatureSummary.cmake.
cmake FIND_LIBRARY_USE_OPENBSD_VERSIONING FIND\_LIBRARY\_USE\_OPENBSD\_VERSIONING
=======================================
Whether [`find_library()`](../command/find_library#command:find_library "find_library") should find OpenBSD-style shared libraries.
This property is a boolean specifying whether the [`find_library()`](../command/find_library#command:find_library "find_library") command should find shared libraries with OpenBSD-style versioned extension: “.so.<major>.<minor>”. The property is set to true on OpenBSD and false on other platforms.
cmake JOB_POOLS JOB\_POOLS
==========
Ninja only: List of available pools.
A pool is a named integer property and defines the maximum number of concurrent jobs which can be started by a rule assigned to the pool. The [`JOB_POOLS`](#prop_gbl:JOB_POOLS "JOB_POOLS") property is a semicolon-separated list of pairs using the syntax NAME=integer (without a space after the equality sign).
For instance:
```
set_property(GLOBAL PROPERTY JOB_POOLS two_jobs=2 ten_jobs=10)
```
Defined pools could be used globally by setting [`CMAKE_JOB_POOL_COMPILE`](../variable/cmake_job_pool_compile#variable:CMAKE_JOB_POOL_COMPILE "CMAKE_JOB_POOL_COMPILE") and [`CMAKE_JOB_POOL_LINK`](../variable/cmake_job_pool_link#variable:CMAKE_JOB_POOL_LINK "CMAKE_JOB_POOL_LINK") or per target by setting the target properties [`JOB_POOL_COMPILE`](../prop_tgt/job_pool_compile#prop_tgt:JOB_POOL_COMPILE "JOB_POOL_COMPILE") and [`JOB_POOL_LINK`](../prop_tgt/job_pool_link#prop_tgt:JOB_POOL_LINK "JOB_POOL_LINK").
Build targets provided by CMake that are meant for individual interactive use, such as `install`, are placed in the `console` pool automatically.
cmake cmake-generators(7) cmake-generators(7)
===================
* [Introduction](#introduction)
* [CMake Generators](#cmake-generators)
+ [Command-Line Build Tool Generators](#command-line-build-tool-generators)
- [Makefile Generators](#makefile-generators)
- [Ninja Generator](#ninja-generator)
+ [IDE Build Tool Generators](#ide-build-tool-generators)
- [Visual Studio Generators](#visual-studio-generators)
- [Other Generators](#other-generators)
* [Extra Generators](#extra-generators)
Introduction
------------
A *CMake Generator* is responsible for writing the input files for a native build system. Exactly one of the [CMake Generators](#cmake-generators) must be selected for a build tree to determine what native build system is to be used. Optionally one of the [Extra Generators](#extra-generators) may be selected as a variant of some of the [Command-Line Build Tool Generators](#command-line-build-tool-generators) to produce project files for an auxiliary IDE.
CMake Generators are platform-specific so each may be available only on certain platforms. The [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") command-line tool `--help` output lists available generators on the current platform. Use its `-G` option to specify the generator for a new build tree. The [`cmake-gui(1)`](cmake-gui.1#manual:cmake-gui(1) "cmake-gui(1)") offers interactive selection of a generator when creating a new build tree.
CMake Generators
----------------
### Command-Line Build Tool Generators
These generators support command-line build tools. In order to use them, one must launch CMake from a command-line prompt whose environment is already configured for the chosen compiler and build tool.
#### Makefile Generators
* [Borland Makefiles](https://cmake.org/cmake/help/v3.9/generator/Borland%20Makefiles.html)
* [MSYS Makefiles](https://cmake.org/cmake/help/v3.9/generator/MSYS%20Makefiles.html)
* [MinGW Makefiles](https://cmake.org/cmake/help/v3.9/generator/MinGW%20Makefiles.html)
* [NMake Makefiles](https://cmake.org/cmake/help/v3.9/generator/NMake%20Makefiles.html)
* [NMake Makefiles JOM](https://cmake.org/cmake/help/v3.9/generator/NMake%20Makefiles%20JOM.html)
* [Unix Makefiles](https://cmake.org/cmake/help/v3.9/generator/Unix%20Makefiles.html)
* [Watcom WMake](https://cmake.org/cmake/help/v3.9/generator/Watcom%20WMake.html)
#### Ninja Generator
* [Ninja](https://cmake.org/cmake/help/v3.9/generator/Ninja.html)
### IDE Build Tool Generators
These generators support Integrated Development Environment (IDE) project files. Since the IDEs configure their own environment one may launch CMake from any environment.
#### Visual Studio Generators
* [Visual Studio 6](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%206.html)
* [Visual Studio 7](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%207.html)
* [Visual Studio 7 .NET 2003](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%207%20.NET%202003.html)
* [Visual Studio 8 2005](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%208%202005.html)
* [Visual Studio 9 2008](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%209%202008.html)
* [Visual Studio 10 2010](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%2010%202010.html)
* [Visual Studio 11 2012](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%2011%202012.html)
* [Visual Studio 12 2013](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%2012%202013.html)
* [Visual Studio 14 2015](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%2014%202015.html)
* [Visual Studio 15 2017](https://cmake.org/cmake/help/v3.9/generator/Visual%20Studio%2015%202017.html)
#### Other Generators
* [Green Hills MULTI](https://cmake.org/cmake/help/v3.9/generator/Green%20Hills%20MULTI.html)
* [Xcode](https://cmake.org/cmake/help/v3.9/generator/Xcode.html)
Extra Generators
----------------
Some of the [CMake Generators](#cmake-generators) listed in the [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") command-line tool `--help` output may have variants that specify an extra generator for an auxiliary IDE tool. Such generator names have the form `<extra-generator> - <main-generator>`. The following extra generators are known to CMake.
* [CodeBlocks](https://cmake.org/cmake/help/v3.9/generator/CodeBlocks.html)
* [CodeLite](https://cmake.org/cmake/help/v3.9/generator/CodeLite.html)
* [Eclipse CDT4](https://cmake.org/cmake/help/v3.9/generator/Eclipse%20CDT4.html)
* [KDevelop3](https://cmake.org/cmake/help/v3.9/generator/KDevelop3.html)
* [Kate](https://cmake.org/cmake/help/v3.9/generator/Kate.html)
* [Sublime Text 2](https://cmake.org/cmake/help/v3.9/generator/Sublime%20Text%202.html)
| programming_docs |
cmake cmake-buildsystem(7) cmake-buildsystem(7)
====================
* [Introduction](#introduction)
* [Binary Targets](#binary-targets)
+ [Binary Executables](#binary-executables)
+ [Binary Library Types](#binary-library-types)
- [Normal Libraries](#normal-libraries)
* [Apple Frameworks](#apple-frameworks)
- [Object Libraries](#object-libraries)
* [Build Specification and Usage Requirements](#build-specification-and-usage-requirements)
+ [Target Properties](#target-properties)
+ [Transitive Usage Requirements](#transitive-usage-requirements)
+ [Compatible Interface Properties](#compatible-interface-properties)
+ [Property Origin Debugging](#property-origin-debugging)
+ [Build Specification with Generator Expressions](#build-specification-with-generator-expressions)
- [Include Directories and Usage Requirements](#include-directories-and-usage-requirements)
+ [Link Libraries and Generator Expressions](#link-libraries-and-generator-expressions)
+ [Output Artifacts](#output-artifacts)
- [Runtime Output Artifacts](#runtime-output-artifacts)
- [Library Output Artifacts](#library-output-artifacts)
- [Archive Output Artifacts](#archive-output-artifacts)
+ [Directory-Scoped Commands](#directory-scoped-commands)
* [Pseudo Targets](#pseudo-targets)
+ [Imported Targets](#imported-targets)
+ [Alias Targets](#alias-targets)
+ [Interface Libraries](#interface-libraries)
Introduction
------------
A CMake-based buildsystem is organized as a set of high-level logical targets. Each target corresponds to an executable or library, or is a custom target containing custom commands. Dependencies between the targets are expressed in the buildsystem to determine the build order and the rules for regeneration in response to change.
Binary Targets
--------------
Executables and libraries are defined using the [`add_executable()`](../command/add_executable#command:add_executable "add_executable") and [`add_library()`](../command/add_library#command:add_library "add_library") commands. The resulting binary files have appropriate prefixes, suffixes and extensions for the platform targeted. Dependencies between binary targets are expressed using the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command:
```
add_library(archive archive.cpp zip.cpp lzma.cpp)
add_executable(zipapp zipapp.cpp)
target_link_libraries(zipapp archive)
```
`archive` is defined as a static library – an archive containing objects compiled from `archive.cpp`, `zip.cpp`, and `lzma.cpp`. `zipapp` is defined as an executable formed by compiling and linking `zipapp.cpp`. When linking the `zipapp` executable, the `archive` static library is linked in.
### Binary Executables
The [`add_executable()`](../command/add_executable#command:add_executable "add_executable") command defines an executable target:
```
add_executable(mytool mytool.cpp)
```
Commands such as [`add_custom_command()`](../command/add_custom_command#command:add_custom_command "add_custom_command"), which generates rules to be run at build time can transparently use an [`EXECUTABLE`](../prop_tgt/type#prop_tgt:TYPE "TYPE") target as a `COMMAND` executable. The buildsystem rules will ensure that the executable is built before attempting to run the command.
### Binary Library Types
#### Normal Libraries
By default, the [`add_library()`](../command/add_library#command:add_library "add_library") command defines a static library, unless a type is specified. A type may be specified when using the command:
```
add_library(archive SHARED archive.cpp zip.cpp lzma.cpp)
```
```
add_library(archive STATIC archive.cpp zip.cpp lzma.cpp)
```
The [`BUILD_SHARED_LIBS`](../variable/build_shared_libs#variable:BUILD_SHARED_LIBS "BUILD_SHARED_LIBS") variable may be enabled to change the behavior of [`add_library()`](../command/add_library#command:add_library "add_library") to build shared libraries by default.
In the context of the buildsystem definition as a whole, it is largely irrelevant whether particular libraries are `SHARED` or `STATIC` – the commands, dependency specifications and other APIs work similarly regardless of the library type. The `MODULE` library type is dissimilar in that it is generally not linked to – it is not used in the right-hand-side of the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command. It is a type which is loaded as a plugin using runtime techniques. If the library does not export any unmanaged symbols (e.g. Windows resource DLL, C++/CLI DLL), it is required that the library not be a `SHARED` library because CMake expects `SHARED` libraries to export at least one symbol.
```
add_library(archive MODULE 7z.cpp)
```
##### Apple Frameworks
A `SHARED` library may be marked with the [`FRAMEWORK`](../prop_tgt/framework#prop_tgt:FRAMEWORK "FRAMEWORK") target property to create an OS X or iOS Framework Bundle. The `MACOSX_FRAMEWORK_IDENTIFIER` sets `CFBundleIdentifier` key and it uniquely identifies the bundle.
```
add_library(MyFramework SHARED MyFramework.cpp)
set_target_properties(MyFramework PROPERTIES
FRAMEWORK TRUE
FRAMEWORK_VERSION A
MACOSX_FRAMEWORK_IDENTIFIER org.cmake.MyFramework
)
```
#### Object Libraries
The `OBJECT` library type is also not linked to. It defines a non-archival collection of object files resulting from compiling the given source files. The object files collection can be used as source inputs to other targets:
```
add_library(archive OBJECT archive.cpp zip.cpp lzma.cpp)
add_library(archiveExtras STATIC $<TARGET_OBJECTS:archive> extras.cpp)
add_executable(test_exe $<TARGET_OBJECTS:archive> test.cpp)
```
`OBJECT` libraries may not be used in the right hand side of [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries"). They also may not be used as the `TARGET` in a use of the [`add_custom_command(TARGET)`](../command/add_custom_command#command:add_custom_command "add_custom_command") command signature. They may be installed, and will be exported as an INTERFACE library.
Although object libraries may not be named directly in calls to the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command, they can be “linked” indirectly by using an [Interface Library](#interface-libraries) whose [`INTERFACE_SOURCES`](../prop_tgt/interface_sources#prop_tgt:INTERFACE_SOURCES "INTERFACE_SOURCES") target property is set to name `$<TARGET_OBJECTS:objlib>`.
Although object libraries may not be used as the `TARGET` in a use of the [`add_custom_command(TARGET)`](../command/add_custom_command#command:add_custom_command "add_custom_command") command signature, the list of objects can be used by [`add_custom_command(OUTPUT)`](../command/add_custom_command#command:add_custom_command "add_custom_command") or [`file(GENERATE)`](../command/file#command:file "file") by using `$<TARGET_OBJECTS:objlib>`.
Build Specification and Usage Requirements
------------------------------------------
The [`target_include_directories()`](../command/target_include_directories#command:target_include_directories "target_include_directories"), [`target_compile_definitions()`](../command/target_compile_definitions#command:target_compile_definitions "target_compile_definitions") and [`target_compile_options()`](../command/target_compile_options#command:target_compile_options "target_compile_options") commands specify the build specifications and the usage requirements of binary targets. The commands populate the [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES"), [`COMPILE_DEFINITIONS`](../prop_tgt/compile_definitions#prop_tgt:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") and [`COMPILE_OPTIONS`](../prop_tgt/compile_options#prop_tgt:COMPILE_OPTIONS "COMPILE_OPTIONS") target properties respectively, and/or the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES"), [`INTERFACE_COMPILE_DEFINITIONS`](../prop_tgt/interface_compile_definitions#prop_tgt:INTERFACE_COMPILE_DEFINITIONS "INTERFACE_COMPILE_DEFINITIONS") and [`INTERFACE_COMPILE_OPTIONS`](../prop_tgt/interface_compile_options#prop_tgt:INTERFACE_COMPILE_OPTIONS "INTERFACE_COMPILE_OPTIONS") target properties.
Each of the commands has a `PRIVATE`, `PUBLIC` and `INTERFACE` mode. The `PRIVATE` mode populates only the non-`INTERFACE_` variant of the target property and the `INTERFACE` mode populates only the `INTERFACE_` variants. The `PUBLIC` mode populates both variants of the respective target property. Each command may be invoked with multiple uses of each keyword:
```
target_compile_definitions(archive
PRIVATE BUILDING_WITH_LZMA
INTERFACE USING_ARCHIVE_LIB
)
```
Note that usage requirements are not designed as a way to make downstreams use particular [`COMPILE_OPTIONS`](../prop_tgt/compile_options#prop_tgt:COMPILE_OPTIONS "COMPILE_OPTIONS") or [`COMPILE_DEFINITIONS`](../prop_tgt/compile_definitions#prop_tgt:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") etc for convenience only. The contents of the properties must be **requirements**, not merely recommendations or convenience.
See the [Creating Relocatable Packages](cmake-packages.7#creating-relocatable-packages) section of the [`cmake-packages(7)`](cmake-packages.7#manual:cmake-packages(7) "cmake-packages(7)") manual for discussion of additional care that must be taken when specifying usage requirements while creating packages for redistribution.
### Target Properties
The contents of the [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES"), [`COMPILE_DEFINITIONS`](../prop_tgt/compile_definitions#prop_tgt:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") and [`COMPILE_OPTIONS`](../prop_tgt/compile_options#prop_tgt:COMPILE_OPTIONS "COMPILE_OPTIONS") target properties are used appropriately when compiling the source files of a binary target.
Entries in the [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES") are added to the compile line with `-I` or `-isystem` prefixes and in the order of appearance in the property value.
Entries in the [`COMPILE_DEFINITIONS`](../prop_tgt/compile_definitions#prop_tgt:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") are prefixed with `-D` or `/D` and added to the compile line in an unspecified order. The [`DEFINE_SYMBOL`](../prop_tgt/define_symbol#prop_tgt:DEFINE_SYMBOL "DEFINE_SYMBOL") target property is also added as a compile definition as a special convenience case for `SHARED` and `MODULE` library targets.
Entries in the [`COMPILE_OPTIONS`](../prop_tgt/compile_options#prop_tgt:COMPILE_OPTIONS "COMPILE_OPTIONS") are escaped for the shell and added in the order of appearance in the property value. Several compile options have special separate handling, such as [`POSITION_INDEPENDENT_CODE`](../prop_tgt/position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE").
The contents of the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES"), [`INTERFACE_COMPILE_DEFINITIONS`](../prop_tgt/interface_compile_definitions#prop_tgt:INTERFACE_COMPILE_DEFINITIONS "INTERFACE_COMPILE_DEFINITIONS") and [`INTERFACE_COMPILE_OPTIONS`](../prop_tgt/interface_compile_options#prop_tgt:INTERFACE_COMPILE_OPTIONS "INTERFACE_COMPILE_OPTIONS") target properties are *Usage Requirements* – they specify content which consumers must use to correctly compile and link with the target they appear on. For any binary target, the contents of each `INTERFACE_` property on each target specified in a [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command is consumed:
```
set(srcs archive.cpp zip.cpp)
if (LZMA_FOUND)
list(APPEND srcs lzma.cpp)
endif()
add_library(archive SHARED ${srcs})
if (LZMA_FOUND)
# The archive library sources are compiled with -DBUILDING_WITH_LZMA
target_compile_definitions(archive PRIVATE BUILDING_WITH_LZMA)
endif()
target_compile_definitions(archive INTERFACE USING_ARCHIVE_LIB)
add_executable(consumer)
# Link consumer to archive and consume its usage requirements. The consumer
# executable sources are compiled with -DUSING_ARCHIVE_LIB.
target_link_libraries(consumer archive)
```
Because it is common to require that the source directory and corresponding build directory are added to the [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES"), the [`CMAKE_INCLUDE_CURRENT_DIR`](../variable/cmake_include_current_dir#variable:CMAKE_INCLUDE_CURRENT_DIR "CMAKE_INCLUDE_CURRENT_DIR") variable can be enabled to conveniently add the corresponding directories to the [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES") of all targets. The variable [`CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE`](../variable/cmake_include_current_dir_in_interface#variable:CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE "CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE") can be enabled to add the corresponding directories to the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") of all targets. This makes use of targets in multiple different directories convenient through use of the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command.
### Transitive Usage Requirements
The usage requirements of a target can transitively propagate to dependents. The [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command has `PRIVATE`, `INTERFACE` and `PUBLIC` keywords to control the propagation.
```
add_library(archive archive.cpp)
target_compile_definitions(archive INTERFACE USING_ARCHIVE_LIB)
add_library(serialization serialization.cpp)
target_compile_definitions(serialization INTERFACE USING_SERIALIZATION_LIB)
add_library(archiveExtras extras.cpp)
target_link_libraries(archiveExtras PUBLIC archive)
target_link_libraries(archiveExtras PRIVATE serialization)
# archiveExtras is compiled with -DUSING_ARCHIVE_LIB
# and -DUSING_SERIALIZATION_LIB
add_executable(consumer consumer.cpp)
# consumer is compiled with -DUSING_ARCHIVE_LIB
target_link_libraries(consumer archiveExtras)
```
Because `archive` is a `PUBLIC` dependency of `archiveExtras`, the usage requirements of it are propagated to `consumer` too. Because `serialization` is a `PRIVATE` dependency of `archive`, the usage requirements of it are not propagated to `consumer`.
Generally, a dependency should be specified in a use of [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") with the `PRIVATE` keyword if it is used by only the implementation of a library, and not in the header files. If a dependency is additionally used in the header files of a library (e.g. for class inheritance), then it should be specified as a `PUBLIC` dependency. A dependency which is not used by the implementation of a library, but only by its headers should be specified as an `INTERFACE` dependency. The [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command may be invoked with multiple uses of each keyword:
```
target_link_libraries(archiveExtras
PUBLIC archive
PRIVATE serialization
)
```
Usage requirements are propagated by reading the `INTERFACE_` variants of target properties from dependencies and appending the values to the non-`INTERFACE_` variants of the operand. For example, the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") of dependencies is read and appended to the [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES") of the operand. In cases where order is relevant and maintained, and the order resulting from the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") calls does not allow correct compilation, use of an appropriate command to set the property directly may update the order.
For example, if the linked libraries for a target must be specified in the order `lib1` `lib2` `lib3` , but the include directories must be specified in the order `lib3` `lib1` `lib2`:
```
target_link_libraries(myExe lib1 lib2 lib3)
target_include_directories(myExe
PRIVATE $<TARGET_PROPERTY:lib3,INTERFACE_INCLUDE_DIRECTORIES>)
```
Note that care must be taken when specifying usage requirements for targets which will be exported for installation using the [`install(EXPORT)`](../command/install#command:install "install") command. See [Creating Packages](cmake-packages.7#creating-packages) for more.
### Compatible Interface Properties
Some target properties are required to be compatible between a target and the interface of each dependency. For example, the [`POSITION_INDEPENDENT_CODE`](../prop_tgt/position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE") target property may specify a boolean value of whether a target should be compiled as position-independent-code, which has platform-specific consequences. A target may also specify the usage requirement [`INTERFACE_POSITION_INDEPENDENT_CODE`](../prop_tgt/interface_position_independent_code#prop_tgt:INTERFACE_POSITION_INDEPENDENT_CODE "INTERFACE_POSITION_INDEPENDENT_CODE") to communicate that consumers must be compiled as position-independent-code.
```
add_executable(exe1 exe1.cpp)
set_property(TARGET exe1 PROPERTY POSITION_INDEPENDENT_CODE ON)
add_library(lib1 SHARED lib1.cpp)
set_property(TARGET lib1 PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE ON)
add_executable(exe2 exe2.cpp)
target_link_libraries(exe2 lib1)
```
Here, both `exe1` and `exe2` will be compiled as position-independent-code. `lib1` will also be compiled as position-independent-code because that is the default setting for `SHARED` libraries. If dependencies have conflicting, non-compatible requirements [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") issues a diagnostic:
```
add_library(lib1 SHARED lib1.cpp)
set_property(TARGET lib1 PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE ON)
add_library(lib2 SHARED lib2.cpp)
set_property(TARGET lib2 PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE OFF)
add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 lib1)
set_property(TARGET exe1 PROPERTY POSITION_INDEPENDENT_CODE OFF)
add_executable(exe2 exe2.cpp)
target_link_libraries(exe2 lib1 lib2)
```
The `lib1` requirement `INTERFACE_POSITION_INDEPENDENT_CODE` is not “compatible” with the `POSITION_INDEPENDENT_CODE` property of the `exe1` target. The library requires that consumers are built as position-independent-code, while the executable specifies to not built as position-independent-code, so a diagnostic is issued.
The `lib1` and `lib2` requirements are not “compatible”. One of them requires that consumers are built as position-independent-code, while the other requires that consumers are not built as position-independent-code. Because `exe2` links to both and they are in conflict, a diagnostic is issued.
To be “compatible”, the [`POSITION_INDEPENDENT_CODE`](../prop_tgt/position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE") property, if set must be either the same, in a boolean sense, as the [`INTERFACE_POSITION_INDEPENDENT_CODE`](../prop_tgt/interface_position_independent_code#prop_tgt:INTERFACE_POSITION_INDEPENDENT_CODE "INTERFACE_POSITION_INDEPENDENT_CODE") property of all transitively specified dependencies on which that property is set.
This property of “compatible interface requirement” may be extended to other properties by specifying the property in the content of the [`COMPATIBLE_INTERFACE_BOOL`](../prop_tgt/compatible_interface_bool#prop_tgt:COMPATIBLE_INTERFACE_BOOL "COMPATIBLE_INTERFACE_BOOL") target property. Each specified property must be compatible between the consuming target and the corresponding property with an `INTERFACE_` prefix from each dependency:
```
add_library(lib1Version2 SHARED lib1_v2.cpp)
set_property(TARGET lib1Version2 PROPERTY INTERFACE_CUSTOM_PROP ON)
set_property(TARGET lib1Version2 APPEND PROPERTY
COMPATIBLE_INTERFACE_BOOL CUSTOM_PROP
)
add_library(lib1Version3 SHARED lib1_v3.cpp)
set_property(TARGET lib1Version3 PROPERTY INTERFACE_CUSTOM_PROP OFF)
add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 lib1Version2) # CUSTOM_PROP will be ON
add_executable(exe2 exe2.cpp)
target_link_libraries(exe2 lib1Version2 lib1Version3) # Diagnostic
```
Non-boolean properties may also participate in “compatible interface” computations. Properties specified in the [`COMPATIBLE_INTERFACE_STRING`](../prop_tgt/compatible_interface_string#prop_tgt:COMPATIBLE_INTERFACE_STRING "COMPATIBLE_INTERFACE_STRING") property must be either unspecified or compare to the same string among all transitively specified dependencies. This can be useful to ensure that multiple incompatible versions of a library are not linked together through transitive requirements of a target:
```
add_library(lib1Version2 SHARED lib1_v2.cpp)
set_property(TARGET lib1Version2 PROPERTY INTERFACE_LIB_VERSION 2)
set_property(TARGET lib1Version2 APPEND PROPERTY
COMPATIBLE_INTERFACE_STRING LIB_VERSION
)
add_library(lib1Version3 SHARED lib1_v3.cpp)
set_property(TARGET lib1Version3 PROPERTY INTERFACE_LIB_VERSION 3)
add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 lib1Version2) # LIB_VERSION will be "2"
add_executable(exe2 exe2.cpp)
target_link_libraries(exe2 lib1Version2 lib1Version3) # Diagnostic
```
The [`COMPATIBLE_INTERFACE_NUMBER_MAX`](../prop_tgt/compatible_interface_number_max#prop_tgt:COMPATIBLE_INTERFACE_NUMBER_MAX "COMPATIBLE_INTERFACE_NUMBER_MAX") target property specifies that content will be evaluated numerically and the maximum number among all specified will be calculated:
```
add_library(lib1Version2 SHARED lib1_v2.cpp)
set_property(TARGET lib1Version2 PROPERTY INTERFACE_CONTAINER_SIZE_REQUIRED 200)
set_property(TARGET lib1Version2 APPEND PROPERTY
COMPATIBLE_INTERFACE_NUMBER_MAX CONTAINER_SIZE_REQUIRED
)
add_library(lib1Version3 SHARED lib1_v3.cpp)
set_property(TARGET lib1Version3 PROPERTY INTERFACE_CONTAINER_SIZE_REQUIRED 1000)
add_executable(exe1 exe1.cpp)
# CONTAINER_SIZE_REQUIRED will be "200"
target_link_libraries(exe1 lib1Version2)
add_executable(exe2 exe2.cpp)
# CONTAINER_SIZE_REQUIRED will be "1000"
target_link_libraries(exe2 lib1Version2 lib1Version3)
```
Similarly, the [`COMPATIBLE_INTERFACE_NUMBER_MIN`](../prop_tgt/compatible_interface_number_min#prop_tgt:COMPATIBLE_INTERFACE_NUMBER_MIN "COMPATIBLE_INTERFACE_NUMBER_MIN") may be used to calculate the numeric minimum value for a property from dependencies.
Each calculated “compatible” property value may be read in the consumer at generate-time using generator expressions.
Note that for each dependee, the set of properties specified in each compatible interface property must not intersect with the set specified in any of the other properties.
### Property Origin Debugging
Because build specifications can be determined by dependencies, the lack of locality of code which creates a target and code which is responsible for setting build specifications may make the code more difficult to reason about. [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") provides a debugging facility to print the origin of the contents of properties which may be determined by dependencies. The properties which can be debugged are listed in the [`CMAKE_DEBUG_TARGET_PROPERTIES`](../variable/cmake_debug_target_properties#variable:CMAKE_DEBUG_TARGET_PROPERTIES "CMAKE_DEBUG_TARGET_PROPERTIES") variable documentation:
```
set(CMAKE_DEBUG_TARGET_PROPERTIES
INCLUDE_DIRECTORIES
COMPILE_DEFINITIONS
POSITION_INDEPENDENT_CODE
CONTAINER_SIZE_REQUIRED
LIB_VERSION
)
add_executable(exe1 exe1.cpp)
```
In the case of properties listed in [`COMPATIBLE_INTERFACE_BOOL`](../prop_tgt/compatible_interface_bool#prop_tgt:COMPATIBLE_INTERFACE_BOOL "COMPATIBLE_INTERFACE_BOOL") or [`COMPATIBLE_INTERFACE_STRING`](../prop_tgt/compatible_interface_string#prop_tgt:COMPATIBLE_INTERFACE_STRING "COMPATIBLE_INTERFACE_STRING"), the debug output shows which target was responsible for setting the property, and which other dependencies also defined the property. In the case of [`COMPATIBLE_INTERFACE_NUMBER_MAX`](../prop_tgt/compatible_interface_number_max#prop_tgt:COMPATIBLE_INTERFACE_NUMBER_MAX "COMPATIBLE_INTERFACE_NUMBER_MAX") and [`COMPATIBLE_INTERFACE_NUMBER_MIN`](../prop_tgt/compatible_interface_number_min#prop_tgt:COMPATIBLE_INTERFACE_NUMBER_MIN "COMPATIBLE_INTERFACE_NUMBER_MIN"), the debug output shows the value of the property from each dependency, and whether the value determines the new extreme.
### Build Specification with Generator Expressions
Build specifications may use [`generator expressions`](cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") containing content which may be conditional or known only at generate-time. For example, the calculated “compatible” value of a property may be read with the `TARGET_PROPERTY` expression:
```
add_library(lib1Version2 SHARED lib1_v2.cpp)
set_property(TARGET lib1Version2 PROPERTY
INTERFACE_CONTAINER_SIZE_REQUIRED 200)
set_property(TARGET lib1Version2 APPEND PROPERTY
COMPATIBLE_INTERFACE_NUMBER_MAX CONTAINER_SIZE_REQUIRED
)
add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 lib1Version2)
target_compile_definitions(exe1 PRIVATE
CONTAINER_SIZE=$<TARGET_PROPERTY:CONTAINER_SIZE_REQUIRED>
)
```
In this case, the `exe1` source files will be compiled with `-DCONTAINER_SIZE=200`.
Configuration determined build specifications may be conveniently set using the `CONFIG` generator expression.
```
target_compile_definitions(exe1 PRIVATE
$<$<CONFIG:Debug>:DEBUG_BUILD>
)
```
The `CONFIG` parameter is compared case-insensitively with the configuration being built. In the presence of [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets, the content of [`MAP_IMPORTED_CONFIG_DEBUG`](# "MAP_IMPORTED_CONFIG_<CONFIG>") is also accounted for by this expression.
Some buildsystems generated by [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") have a predetermined build-configuration set in the [`CMAKE_BUILD_TYPE`](../variable/cmake_build_type#variable:CMAKE_BUILD_TYPE "CMAKE_BUILD_TYPE") variable. The buildsystem for the IDEs such as Visual Studio and Xcode are generated independent of the build-configuration, and the actual build configuration is not known until build-time. Therefore, code such as
```
string(TOLOWER ${CMAKE_BUILD_TYPE} _type)
if (_type STREQUAL debug)
target_compile_definitions(exe1 PRIVATE DEBUG_BUILD)
endif()
```
may appear to work for `Makefile` based and `Ninja` generators, but is not portable to IDE generators. Additionally, the [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") configuration-mappings are not accounted for with code like this, so it should be avoided.
The unary `TARGET_PROPERTY` generator expression and the `TARGET_POLICY` generator expression are evaluated with the consuming target context. This means that a usage requirement specification may be evaluated differently based on the consumer:
```
add_library(lib1 lib1.cpp)
target_compile_definitions(lib1 INTERFACE
$<$<STREQUAL:$<TARGET_PROPERTY:TYPE>,EXECUTABLE>:LIB1_WITH_EXE>
$<$<STREQUAL:$<TARGET_PROPERTY:TYPE>,SHARED_LIBRARY>:LIB1_WITH_SHARED_LIB>
$<$<TARGET_POLICY:CMP0041>:CONSUMER_CMP0041_NEW>
)
add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 lib1)
cmake_policy(SET CMP0041 NEW)
add_library(shared_lib shared_lib.cpp)
target_link_libraries(shared_lib lib1)
```
The `exe1` executable will be compiled with `-DLIB1_WITH_EXE`, while the `shared_lib` shared library will be compiled with `-DLIB1_WITH_SHARED_LIB` and `-DCONSUMER_CMP0041_NEW`, because policy [`CMP0041`](../policy/cmp0041#policy:CMP0041 "CMP0041") is `NEW` at the point where the `shared_lib` target is created.
The `BUILD_INTERFACE` expression wraps requirements which are only used when consumed from a target in the same buildsystem, or when consumed from a target exported to the build directory using the [`export()`](../command/export#command:export "export") command. The `INSTALL_INTERFACE` expression wraps requirements which are only used when consumed from a target which has been installed and exported with the [`install(EXPORT)`](../command/install#command:install "install") command:
```
add_library(ClimbingStats climbingstats.cpp)
target_compile_definitions(ClimbingStats INTERFACE
$<BUILD_INTERFACE:ClimbingStats_FROM_BUILD_LOCATION>
$<INSTALL_INTERFACE:ClimbingStats_FROM_INSTALLED_LOCATION>
)
install(TARGETS ClimbingStats EXPORT libExport ${InstallArgs})
install(EXPORT libExport NAMESPACE Upstream::
DESTINATION lib/cmake/ClimbingStats)
export(EXPORT libExport NAMESPACE Upstream::)
add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 ClimbingStats)
```
In this case, the `exe1` executable will be compiled with `-DClimbingStats_FROM_BUILD_LOCATION`. The exporting commands generate [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets with either the `INSTALL_INTERFACE` or the `BUILD_INTERFACE` omitted, and the `*_INTERFACE` marker stripped away. A separate project consuming the `ClimbingStats` package would contain:
```
find_package(ClimbingStats REQUIRED)
add_executable(Downstream main.cpp)
target_link_libraries(Downstream Upstream::ClimbingStats)
```
Depending on whether the `ClimbingStats` package was used from the build location or the install location, the `Downstream` target would be compiled with either `-DClimbingStats_FROM_BUILD_LOCATION` or `-DClimbingStats_FROM_INSTALL_LOCATION`. For more about packages and exporting see the [`cmake-packages(7)`](cmake-packages.7#manual:cmake-packages(7) "cmake-packages(7)") manual.
#### Include Directories and Usage Requirements
Include directories require some special consideration when specified as usage requirements and when used with generator expressions. The [`target_include_directories()`](../command/target_include_directories#command:target_include_directories "target_include_directories") command accepts both relative and absolute include directories:
```
add_library(lib1 lib1.cpp)
target_include_directories(lib1 PRIVATE
/absolute/path
relative/path
)
```
Relative paths are interpreted relative to the source directory where the command appears. Relative paths are not allowed in the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") of [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets.
In cases where a non-trivial generator expression is used, the `INSTALL_PREFIX` expression may be used within the argument of an `INSTALL_INTERFACE` expression. It is a replacement marker which expands to the installation prefix when imported by a consuming project.
Include directories usage requirements commonly differ between the build-tree and the install-tree. The `BUILD_INTERFACE` and `INSTALL_INTERFACE` generator expressions can be used to describe separate usage requirements based on the usage location. Relative paths are allowed within the `INSTALL_INTERFACE` expression and are interpreted relative to the installation prefix. For example:
```
add_library(ClimbingStats climbingstats.cpp)
target_include_directories(ClimbingStats INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}/generated>
$<INSTALL_INTERFACE:/absolute/path>
$<INSTALL_INTERFACE:relative/path>
$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/$<CONFIG>/generated>
)
```
Two convenience APIs are provided relating to include directories usage requirements. The [`CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE`](../variable/cmake_include_current_dir_in_interface#variable:CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE "CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE") variable may be enabled, with an equivalent effect to:
```
set_property(TARGET tgt APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR};${CMAKE_CURRENT_BINARY_DIR}>
)
```
for each target affected. The convenience for installed targets is an `INCLUDES DESTINATION` component with the [`install(TARGETS)`](../command/install#command:install "install") command:
```
install(TARGETS foo bar bat EXPORT tgts ${dest_args}
INCLUDES DESTINATION include
)
install(EXPORT tgts ${other_args})
install(FILES ${headers} DESTINATION include)
```
This is equivalent to appending `${CMAKE_INSTALL_PREFIX}/include` to the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") of each of the installed [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets when generated by [`install(EXPORT)`](../command/install#command:install "install").
When the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") of an [imported target](#imported-targets) is consumed, the entries in the property are treated as `SYSTEM` include directories, as if they were listed in the [`INTERFACE_SYSTEM_INCLUDE_DIRECTORIES`](../prop_tgt/interface_system_include_directories#prop_tgt:INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "INTERFACE_SYSTEM_INCLUDE_DIRECTORIES") of the dependency. This can result in omission of compiler warnings for headers found in those directories. This behavior for [Imported Targets](#imported-targets) may be controlled with the [`NO_SYSTEM_FROM_IMPORTED`](../prop_tgt/no_system_from_imported#prop_tgt:NO_SYSTEM_FROM_IMPORTED "NO_SYSTEM_FROM_IMPORTED") target property.
If a binary target is linked transitively to a Mac OX framework, the `Headers` directory of the framework is also treated as a usage requirement. This has the same effect as passing the framework directory as an include directory.
### Link Libraries and Generator Expressions
Like build specifications, [`link libraries`](../prop_tgt/link_libraries#prop_tgt:LINK_LIBRARIES "LINK_LIBRARIES") may be specified with generator expression conditions. However, as consumption of usage requirements is based on collection from linked dependencies, there is an additional limitation that the link dependencies must form a “directed acyclic graph”. That is, if linking to a target is dependent on the value of a target property, that target property may not be dependent on the linked dependencies:
```
add_library(lib1 lib1.cpp)
add_library(lib2 lib2.cpp)
target_link_libraries(lib1 PUBLIC
$<$<TARGET_PROPERTY:POSITION_INDEPENDENT_CODE>:lib2>
)
add_library(lib3 lib3.cpp)
set_property(TARGET lib3 PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE ON)
add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 lib1 lib3)
```
As the value of the [`POSITION_INDEPENDENT_CODE`](../prop_tgt/position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE") property of the `exe1` target is dependent on the linked libraries (`lib3`), and the edge of linking `exe1` is determined by the same [`POSITION_INDEPENDENT_CODE`](../prop_tgt/position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE") property, the dependency graph above contains a cycle. [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") issues a diagnostic in this case.
### Output Artifacts
The buildsystem targets created by the [`add_library()`](../command/add_library#command:add_library "add_library") and [`add_executable()`](../command/add_executable#command:add_executable "add_executable") commands create rules to create binary outputs. The exact output location of the binaries can only be determined at generate-time because it can depend on the build-configuration and the link-language of linked dependencies etc. `TARGET_FILE`, `TARGET_LINKER_FILE` and related expressions can be used to access the name and location of generated binaries. These expressions do not work for `OBJECT` libraries however, as there is no single file generated by such libraries which is relevant to the expressions.
There are three kinds of output artifacts that may be build by targets as detailed in the following sections. Their classification differs between DLL platforms and non-DLL platforms. All Windows-based systems including Cygwin are DLL platforms.
#### Runtime Output Artifacts
A *runtime* output artifact of a buildsystem target may be:
* The executable file (e.g. `.exe`) of an executable target created by the [`add_executable()`](../command/add_executable#command:add_executable "add_executable") command.
* On DLL platforms: the executable file (e.g. `.dll`) of a shared library target created by the [`add_library()`](../command/add_library#command:add_library "add_library") command with the `SHARED` option.
The [`RUNTIME_OUTPUT_DIRECTORY`](../prop_tgt/runtime_output_directory#prop_tgt:RUNTIME_OUTPUT_DIRECTORY "RUNTIME_OUTPUT_DIRECTORY") and [`RUNTIME_OUTPUT_NAME`](../prop_tgt/runtime_output_name#prop_tgt:RUNTIME_OUTPUT_NAME "RUNTIME_OUTPUT_NAME") target properties may be used to control runtime output artifact locations and names in the build tree.
#### Library Output Artifacts
A *library* output artifact of a buildsystem target may be:
* The loadable module file (e.g. `.dll` or `.so`) of a module library target created by the [`add_library()`](../command/add_library#command:add_library "add_library") command with the `MODULE` option.
* On non-DLL platforms: the shared library file (e.g. `.so` or `.dylib`) of a shared shared library target created by the [`add_library()`](../command/add_library#command:add_library "add_library") command with the `SHARED` option.
The [`LIBRARY_OUTPUT_DIRECTORY`](../prop_tgt/library_output_directory#prop_tgt:LIBRARY_OUTPUT_DIRECTORY "LIBRARY_OUTPUT_DIRECTORY") and [`LIBRARY_OUTPUT_NAME`](../prop_tgt/library_output_name#prop_tgt:LIBRARY_OUTPUT_NAME "LIBRARY_OUTPUT_NAME") target properties may be used to control library output artifact locations and names in the build tree.
#### Archive Output Artifacts
An *archive* output artifact of a buildsystem target may be:
* The static library file (e.g. `.lib` or `.a`) of a static library target created by the [`add_library()`](../command/add_library#command:add_library "add_library") command with the `STATIC` option.
* On DLL platforms: the import library file (e.g. `.lib`) of a shared library target created by the [`add_library()`](../command/add_library#command:add_library "add_library") command with the `SHARED` option. This file is only guaranteed to exist if the library exports at least one unmanaged symbol.
* On DLL platforms: the import library file (e.g. `.lib`) of an executable target created by the [`add_executable()`](../command/add_executable#command:add_executable "add_executable") command when its [`ENABLE_EXPORTS`](../prop_tgt/enable_exports#prop_tgt:ENABLE_EXPORTS "ENABLE_EXPORTS") target property is set.
The [`ARCHIVE_OUTPUT_DIRECTORY`](../prop_tgt/archive_output_directory#prop_tgt:ARCHIVE_OUTPUT_DIRECTORY "ARCHIVE_OUTPUT_DIRECTORY") and [`ARCHIVE_OUTPUT_NAME`](../prop_tgt/archive_output_name#prop_tgt:ARCHIVE_OUTPUT_NAME "ARCHIVE_OUTPUT_NAME") target properties may be used to control archive output artifact locations and names in the build tree.
### Directory-Scoped Commands
The [`target_include_directories()`](../command/target_include_directories#command:target_include_directories "target_include_directories"), [`target_compile_definitions()`](../command/target_compile_definitions#command:target_compile_definitions "target_compile_definitions") and [`target_compile_options()`](../command/target_compile_options#command:target_compile_options "target_compile_options") commands have an effect on only one target at a time. The commands [`add_definitions()`](../command/add_definitions#command:add_definitions "add_definitions"), [`add_compile_options()`](../command/add_compile_options#command:add_compile_options "add_compile_options") and [`include_directories()`](../command/include_directories#command:include_directories "include_directories") have a similar function, but operate at directory scope instead of target scope for convenience.
Pseudo Targets
--------------
Some target types do not represent outputs of the buildsystem, but only inputs such as external dependencies, aliases or other non-build artifacts. Pseudo targets are not represented in the generated buildsystem.
### Imported Targets
An [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target represents a pre-existing dependency. Usually such targets are defined by an upstream package and should be treated as immutable. It is not possible to use an [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target in the left-hand-side of the [`target_compile_definitions()`](../command/target_compile_definitions#command:target_compile_definitions "target_compile_definitions"), [`target_include_directories()`](../command/target_include_directories#command:target_include_directories "target_include_directories"), [`target_compile_options()`](../command/target_compile_options#command:target_compile_options "target_compile_options") or [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") commands, as that would be an attempt to modify it. [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets are designed to be used only in the right-hand-side of those commands.
[`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets may have the same usage requirement properties populated as binary targets, such as [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES"), [`INTERFACE_COMPILE_DEFINITIONS`](../prop_tgt/interface_compile_definitions#prop_tgt:INTERFACE_COMPILE_DEFINITIONS "INTERFACE_COMPILE_DEFINITIONS"), [`INTERFACE_COMPILE_OPTIONS`](../prop_tgt/interface_compile_options#prop_tgt:INTERFACE_COMPILE_OPTIONS "INTERFACE_COMPILE_OPTIONS"), [`INTERFACE_LINK_LIBRARIES`](../prop_tgt/interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES"), and [`INTERFACE_POSITION_INDEPENDENT_CODE`](../prop_tgt/interface_position_independent_code#prop_tgt:INTERFACE_POSITION_INDEPENDENT_CODE "INTERFACE_POSITION_INDEPENDENT_CODE").
The [`LOCATION`](../prop_tgt/location#prop_tgt:LOCATION "LOCATION") may also be read from an IMPORTED target, though there is rarely reason to do so. Commands such as [`add_custom_command()`](../command/add_custom_command#command:add_custom_command "add_custom_command") can transparently use an [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") [`EXECUTABLE`](../prop_tgt/type#prop_tgt:TYPE "TYPE") target as a `COMMAND` executable.
The scope of the definition of an [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target is the directory where it was defined. It may be accessed and used from subdirectories, but not from parent directories or sibling directories. The scope is similar to the scope of a cmake variable.
It is also possible to define a `GLOBAL` [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target which is accessible globally in the buildsystem.
See the [`cmake-packages(7)`](cmake-packages.7#manual:cmake-packages(7) "cmake-packages(7)") manual for more on creating packages with [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets.
### Alias Targets
An `ALIAS` target is a name which may be used interchangeably with a binary target name in read-only contexts. A primary use-case for `ALIAS` targets is for example or unit test executables accompanying a library, which may be part of the same buildsystem or built separately based on user configuration.
```
add_library(lib1 lib1.cpp)
install(TARGETS lib1 EXPORT lib1Export ${dest_args})
install(EXPORT lib1Export NAMESPACE Upstream:: ${other_args})
add_library(Upstream::lib1 ALIAS lib1)
```
In another directory, we can link unconditionally to the `Upstream::lib1` target, which may be an [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target from a package, or an `ALIAS` target if built as part of the same buildsystem.
```
if (NOT TARGET Upstream::lib1)
find_package(lib1 REQUIRED)
endif()
add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 Upstream::lib1)
```
`ALIAS` targets are not mutable, installable or exportable. They are entirely local to the buildsystem description. A name can be tested for whether it is an `ALIAS` name by reading the [`ALIASED_TARGET`](../prop_tgt/aliased_target#prop_tgt:ALIASED_TARGET "ALIASED_TARGET") property from it:
```
get_target_property(_aliased Upstream::lib1 ALIASED_TARGET)
if(_aliased)
message(STATUS "The name Upstream::lib1 is an ALIAS for ${_aliased}.")
endif()
```
### Interface Libraries
An `INTERFACE` target has no [`LOCATION`](../prop_tgt/location#prop_tgt:LOCATION "LOCATION") and is mutable, but is otherwise similar to an [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target.
It may specify usage requirements such as [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES"), [`INTERFACE_COMPILE_DEFINITIONS`](../prop_tgt/interface_compile_definitions#prop_tgt:INTERFACE_COMPILE_DEFINITIONS "INTERFACE_COMPILE_DEFINITIONS"), [`INTERFACE_COMPILE_OPTIONS`](../prop_tgt/interface_compile_options#prop_tgt:INTERFACE_COMPILE_OPTIONS "INTERFACE_COMPILE_OPTIONS"), [`INTERFACE_LINK_LIBRARIES`](../prop_tgt/interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES"), [`INTERFACE_SOURCES`](../prop_tgt/interface_sources#prop_tgt:INTERFACE_SOURCES "INTERFACE_SOURCES"), and [`INTERFACE_POSITION_INDEPENDENT_CODE`](../prop_tgt/interface_position_independent_code#prop_tgt:INTERFACE_POSITION_INDEPENDENT_CODE "INTERFACE_POSITION_INDEPENDENT_CODE"). Only the `INTERFACE` modes of the [`target_include_directories()`](../command/target_include_directories#command:target_include_directories "target_include_directories"), [`target_compile_definitions()`](../command/target_compile_definitions#command:target_compile_definitions "target_compile_definitions"), [`target_compile_options()`](../command/target_compile_options#command:target_compile_options "target_compile_options"), [`target_sources()`](../command/target_sources#command:target_sources "target_sources"), and [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") commands may be used with `INTERFACE` libraries.
A primary use-case for `INTERFACE` libraries is header-only libraries.
```
add_library(Eigen INTERFACE)
target_include_directories(Eigen INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src>
$<INSTALL_INTERFACE:include/Eigen>
)
add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 Eigen)
```
Here, the usage requirements from the `Eigen` target are consumed and used when compiling, but it has no effect on linking.
Another use-case is to employ an entirely target-focussed design for usage requirements:
```
add_library(pic_on INTERFACE)
set_property(TARGET pic_on PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE ON)
add_library(pic_off INTERFACE)
set_property(TARGET pic_off PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE OFF)
add_library(enable_rtti INTERFACE)
target_compile_options(enable_rtti INTERFACE
$<$<OR:$<COMPILER_ID:GNU>,$<COMPILER_ID:Clang>>:-rtti>
)
add_executable(exe1 exe1.cpp)
target_link_libraries(exe1 pic_on enable_rtti)
```
This way, the build specification of `exe1` is expressed entirely as linked targets, and the complexity of compiler-specific flags is encapsulated in an `INTERFACE` library target.
The properties permitted to be set on or read from an `INTERFACE` library are:
* Properties matching `INTERFACE_*`
* Built-in properties matching `COMPATIBLE_INTERFACE_*`
* `EXPORT_NAME`
* `IMPORTED`
* `NAME`
* `NO_SYSTEM_FROM_IMPORTED`
* Properties matching `IMPORTED_LIBNAME_*`
* Properties matching `MAP_IMPORTED_CONFIG_*`
`INTERFACE` libraries may be installed and exported. Any content they refer to must be installed separately:
```
add_library(Eigen INTERFACE)
target_include_directories(Eigen INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src>
$<INSTALL_INTERFACE:include/Eigen>
)
install(TARGETS Eigen EXPORT eigenExport)
install(EXPORT eigenExport NAMESPACE Upstream::
DESTINATION lib/cmake/Eigen
)
install(FILES
${CMAKE_CURRENT_SOURCE_DIR}/src/eigen.h
${CMAKE_CURRENT_SOURCE_DIR}/src/vector.h
${CMAKE_CURRENT_SOURCE_DIR}/src/matrix.h
DESTINATION include/Eigen
)
```
| programming_docs |
cmake cmake-variables(7) cmake-variables(7)
==================
* [Variables that Provide Information](#variables-that-provide-information)
* [Variables that Change Behavior](#variables-that-change-behavior)
* [Variables that Describe the System](#variables-that-describe-the-system)
* [Variables that Control the Build](#variables-that-control-the-build)
* [Variables for Languages](#variables-for-languages)
* [Variables for CTest](#variables-for-ctest)
* [Variables for CPack](#variables-for-cpack)
Variables that Provide Information
----------------------------------
* [CMAKE\_AR](../variable/cmake_ar)
* [CMAKE\_ARGC](../variable/cmake_argc)
* [CMAKE\_ARGV0](../variable/cmake_argv0)
* [CMAKE\_BINARY\_DIR](../variable/cmake_binary_dir)
* [CMAKE\_BUILD\_TOOL](../variable/cmake_build_tool)
* [CMAKE\_CACHEFILE\_DIR](../variable/cmake_cachefile_dir)
* [CMAKE\_CACHE\_MAJOR\_VERSION](../variable/cmake_cache_major_version)
* [CMAKE\_CACHE\_MINOR\_VERSION](../variable/cmake_cache_minor_version)
* [CMAKE\_CACHE\_PATCH\_VERSION](../variable/cmake_cache_patch_version)
* [CMAKE\_CFG\_INTDIR](../variable/cmake_cfg_intdir)
* [CMAKE\_COMMAND](../variable/cmake_command)
* [CMAKE\_CROSSCOMPILING](../variable/cmake_crosscompiling)
* [CMAKE\_CROSSCOMPILING\_EMULATOR](../variable/cmake_crosscompiling_emulator)
* [CMAKE\_CTEST\_COMMAND](../variable/cmake_ctest_command)
* [CMAKE\_CURRENT\_BINARY\_DIR](../variable/cmake_current_binary_dir)
* [CMAKE\_CURRENT\_LIST\_DIR](../variable/cmake_current_list_dir)
* [CMAKE\_CURRENT\_LIST\_FILE](../variable/cmake_current_list_file)
* [CMAKE\_CURRENT\_LIST\_LINE](../variable/cmake_current_list_line)
* [CMAKE\_CURRENT\_SOURCE\_DIR](../variable/cmake_current_source_dir)
* [CMAKE\_DL\_LIBS](../variable/cmake_dl_libs)
* [CMAKE\_EDIT\_COMMAND](../variable/cmake_edit_command)
* [CMAKE\_EXECUTABLE\_SUFFIX](../variable/cmake_executable_suffix)
* [CMAKE\_EXTRA\_GENERATOR](../variable/cmake_extra_generator)
* [CMAKE\_EXTRA\_SHARED\_LIBRARY\_SUFFIXES](../variable/cmake_extra_shared_library_suffixes)
* [CMAKE\_FIND\_PACKAGE\_NAME](../variable/cmake_find_package_name)
* [CMAKE\_FIND\_PACKAGE\_SORT\_DIRECTION](../variable/cmake_find_package_sort_direction)
* [CMAKE\_FIND\_PACKAGE\_SORT\_ORDER](../variable/cmake_find_package_sort_order)
* [CMAKE\_GENERATOR](../variable/cmake_generator)
* [CMAKE\_GENERATOR\_PLATFORM](../variable/cmake_generator_platform)
* [CMAKE\_GENERATOR\_TOOLSET](../variable/cmake_generator_toolset)
* [CMAKE\_HOME\_DIRECTORY](../variable/cmake_home_directory)
* [CMAKE\_IMPORT\_LIBRARY\_PREFIX](../variable/cmake_import_library_prefix)
* [CMAKE\_IMPORT\_LIBRARY\_SUFFIX](../variable/cmake_import_library_suffix)
* [CMAKE\_JOB\_POOL\_COMPILE](../variable/cmake_job_pool_compile)
* [CMAKE\_JOB\_POOL\_LINK](../variable/cmake_job_pool_link)
* [CMAKE\_<LANG>\_COMPILER\_AR](../variable/cmake_lang_compiler_ar)
* [CMAKE\_<LANG>\_COMPILER\_RANLIB](../variable/cmake_lang_compiler_ranlib)
* [CMAKE\_LINK\_LIBRARY\_SUFFIX](../variable/cmake_link_library_suffix)
* [CMAKE\_LINK\_SEARCH\_END\_STATIC](../variable/cmake_link_search_end_static)
* [CMAKE\_LINK\_SEARCH\_START\_STATIC](../variable/cmake_link_search_start_static)
* [CMAKE\_MAJOR\_VERSION](../variable/cmake_major_version)
* [CMAKE\_MAKE\_PROGRAM](../variable/cmake_make_program)
* [CMAKE\_MATCH\_COUNT](../variable/cmake_match_count)
* [CMAKE\_MATCH\_<n>](../variable/cmake_match_n)
* [CMAKE\_MINIMUM\_REQUIRED\_VERSION](../variable/cmake_minimum_required_version)
* [CMAKE\_MINOR\_VERSION](../variable/cmake_minor_version)
* [CMAKE\_PARENT\_LIST\_FILE](../variable/cmake_parent_list_file)
* [CMAKE\_PATCH\_VERSION](../variable/cmake_patch_version)
* [CMAKE\_PROJECT\_DESCRIPTION](../variable/cmake_project_description)
* [CMAKE\_PROJECT\_NAME](../variable/cmake_project_name)
* [CMAKE\_RANLIB](../variable/cmake_ranlib)
* [CMAKE\_ROOT](../variable/cmake_root)
* [CMAKE\_SCRIPT\_MODE\_FILE](../variable/cmake_script_mode_file)
* [CMAKE\_SHARED\_LIBRARY\_PREFIX](../variable/cmake_shared_library_prefix)
* [CMAKE\_SHARED\_LIBRARY\_SUFFIX](../variable/cmake_shared_library_suffix)
* [CMAKE\_SHARED\_MODULE\_PREFIX](../variable/cmake_shared_module_prefix)
* [CMAKE\_SHARED\_MODULE\_SUFFIX](../variable/cmake_shared_module_suffix)
* [CMAKE\_SIZEOF\_VOID\_P](../variable/cmake_sizeof_void_p)
* [CMAKE\_SKIP\_INSTALL\_RULES](../variable/cmake_skip_install_rules)
* [CMAKE\_SKIP\_RPATH](../variable/cmake_skip_rpath)
* [CMAKE\_SOURCE\_DIR](../variable/cmake_source_dir)
* [CMAKE\_STATIC\_LIBRARY\_PREFIX](../variable/cmake_static_library_prefix)
* [CMAKE\_STATIC\_LIBRARY\_SUFFIX](../variable/cmake_static_library_suffix)
* [CMAKE\_TOOLCHAIN\_FILE](../variable/cmake_toolchain_file)
* [CMAKE\_TWEAK\_VERSION](../variable/cmake_tweak_version)
* [CMAKE\_VERBOSE\_MAKEFILE](../variable/cmake_verbose_makefile)
* [CMAKE\_VERSION](../variable/cmake_version)
* [CMAKE\_VS\_DEVENV\_COMMAND](../variable/cmake_vs_devenv_command)
* [CMAKE\_VS\_INTEL\_Fortran\_PROJECT\_VERSION](../variable/cmake_vs_intel_fortran_project_version)
* [CMAKE\_VS\_MSBUILD\_COMMAND](../variable/cmake_vs_msbuild_command)
* [CMAKE\_VS\_NsightTegra\_VERSION](../variable/cmake_vs_nsighttegra_version)
* [CMAKE\_VS\_PLATFORM\_NAME](../variable/cmake_vs_platform_name)
* [CMAKE\_VS\_PLATFORM\_TOOLSET](../variable/cmake_vs_platform_toolset)
* [CMAKE\_VS\_PLATFORM\_TOOLSET\_CUDA](../variable/cmake_vs_platform_toolset_cuda)
* [CMAKE\_VS\_PLATFORM\_TOOLSET\_HOST\_ARCHITECTURE](../variable/cmake_vs_platform_toolset_host_architecture)
* [CMAKE\_VS\_WINDOWS\_TARGET\_PLATFORM\_VERSION](../variable/cmake_vs_windows_target_platform_version)
* [CMAKE\_XCODE\_GENERATE\_SCHEME](../variable/cmake_xcode_generate_scheme)
* [CMAKE\_XCODE\_PLATFORM\_TOOLSET](../variable/cmake_xcode_platform_toolset)
* [<PROJECT-NAME>\_BINARY\_DIR](../variable/project-name_binary_dir)
* [<PROJECT-NAME>\_SOURCE\_DIR](../variable/project-name_source_dir)
* [<PROJECT-NAME>\_VERSION](../variable/project-name_version)
* [<PROJECT-NAME>\_VERSION\_MAJOR](../variable/project-name_version_major)
* [<PROJECT-NAME>\_VERSION\_MINOR](../variable/project-name_version_minor)
* [<PROJECT-NAME>\_VERSION\_PATCH](../variable/project-name_version_patch)
* [<PROJECT-NAME>\_VERSION\_TWEAK](../variable/project-name_version_tweak)
* [PROJECT\_BINARY\_DIR](../variable/project_binary_dir)
* [PROJECT\_DESCRIPTION](../variable/project_description)
* [PROJECT\_NAME](../variable/project_name)
* [PROJECT\_SOURCE\_DIR](../variable/project_source_dir)
* [PROJECT\_VERSION](../variable/project_version)
* [PROJECT\_VERSION\_MAJOR](../variable/project_version_major)
* [PROJECT\_VERSION\_MINOR](../variable/project_version_minor)
* [PROJECT\_VERSION\_PATCH](../variable/project_version_patch)
* [PROJECT\_VERSION\_TWEAK](../variable/project_version_tweak)
Variables that Change Behavior
------------------------------
* [BUILD\_SHARED\_LIBS](../variable/build_shared_libs)
* [CMAKE\_ABSOLUTE\_DESTINATION\_FILES](../variable/cmake_absolute_destination_files)
* [CMAKE\_APPBUNDLE\_PATH](../variable/cmake_appbundle_path)
* [CMAKE\_AUTOMOC\_RELAXED\_MODE](../variable/cmake_automoc_relaxed_mode)
* [CMAKE\_BACKWARDS\_COMPATIBILITY](../variable/cmake_backwards_compatibility)
* [CMAKE\_BUILD\_TYPE](../variable/cmake_build_type)
* [CMAKE\_CODELITE\_USE\_TARGETS](../variable/cmake_codelite_use_targets)
* [CMAKE\_COLOR\_MAKEFILE](../variable/cmake_color_makefile)
* [CMAKE\_CONFIGURATION\_TYPES](../variable/cmake_configuration_types)
* [CMAKE\_DEBUG\_TARGET\_PROPERTIES](../variable/cmake_debug_target_properties)
* [CMAKE\_DEPENDS\_IN\_PROJECT\_ONLY](../variable/cmake_depends_in_project_only)
* [CMAKE\_DISABLE\_FIND\_PACKAGE\_<PackageName>](../variable/cmake_disable_find_package_packagename)
* [CMAKE\_ECLIPSE\_GENERATE\_LINKED\_RESOURCES](../variable/cmake_eclipse_generate_linked_resources)
* [CMAKE\_ECLIPSE\_GENERATE\_SOURCE\_PROJECT](../variable/cmake_eclipse_generate_source_project)
* [CMAKE\_ECLIPSE\_MAKE\_ARGUMENTS](../variable/cmake_eclipse_make_arguments)
* [CMAKE\_ECLIPSE\_VERSION](../variable/cmake_eclipse_version)
* [CMAKE\_ERROR\_DEPRECATED](../variable/cmake_error_deprecated)
* [CMAKE\_ERROR\_ON\_ABSOLUTE\_INSTALL\_DESTINATION](../variable/cmake_error_on_absolute_install_destination)
* [CMAKE\_EXPORT\_COMPILE\_COMMANDS](../variable/cmake_export_compile_commands)
* [CMAKE\_EXPORT\_NO\_PACKAGE\_REGISTRY](../variable/cmake_export_no_package_registry)
* [CMAKE\_FIND\_APPBUNDLE](../variable/cmake_find_appbundle)
* [CMAKE\_FIND\_FRAMEWORK](../variable/cmake_find_framework)
* [CMAKE\_FIND\_LIBRARY\_CUSTOM\_LIB\_SUFFIX](../variable/cmake_find_library_custom_lib_suffix)
* [CMAKE\_FIND\_LIBRARY\_PREFIXES](../variable/cmake_find_library_prefixes)
* [CMAKE\_FIND\_LIBRARY\_SUFFIXES](../variable/cmake_find_library_suffixes)
* [CMAKE\_FIND\_NO\_INSTALL\_PREFIX](../variable/cmake_find_no_install_prefix)
* [CMAKE\_FIND\_PACKAGE\_NO\_PACKAGE\_REGISTRY](../variable/cmake_find_package_no_package_registry)
* [CMAKE\_FIND\_PACKAGE\_NO\_SYSTEM\_PACKAGE\_REGISTRY](../variable/cmake_find_package_no_system_package_registry)
* [CMAKE\_FIND\_PACKAGE\_WARN\_NO\_MODULE](../variable/cmake_find_package_warn_no_module)
* [CMAKE\_FIND\_ROOT\_PATH](../variable/cmake_find_root_path)
* [CMAKE\_FIND\_ROOT\_PATH\_MODE\_INCLUDE](../variable/cmake_find_root_path_mode_include)
* [CMAKE\_FIND\_ROOT\_PATH\_MODE\_LIBRARY](../variable/cmake_find_root_path_mode_library)
* [CMAKE\_FIND\_ROOT\_PATH\_MODE\_PACKAGE](../variable/cmake_find_root_path_mode_package)
* [CMAKE\_FIND\_ROOT\_PATH\_MODE\_PROGRAM](../variable/cmake_find_root_path_mode_program)
* [CMAKE\_FRAMEWORK\_PATH](../variable/cmake_framework_path)
* [CMAKE\_IGNORE\_PATH](../variable/cmake_ignore_path)
* [CMAKE\_INCLUDE\_DIRECTORIES\_BEFORE](../variable/cmake_include_directories_before)
* [CMAKE\_INCLUDE\_DIRECTORIES\_PROJECT\_BEFORE](../variable/cmake_include_directories_project_before)
* [CMAKE\_INCLUDE\_PATH](../variable/cmake_include_path)
* [CMAKE\_INSTALL\_DEFAULT\_COMPONENT\_NAME](../variable/cmake_install_default_component_name)
* [CMAKE\_INSTALL\_MESSAGE](../variable/cmake_install_message)
* [CMAKE\_INSTALL\_PREFIX](../variable/cmake_install_prefix)
* [CMAKE\_INSTALL\_PREFIX\_INITIALIZED\_TO\_DEFAULT](../variable/cmake_install_prefix_initialized_to_default)
* [CMAKE\_LIBRARY\_PATH](../variable/cmake_library_path)
* [CMAKE\_MFC\_FLAG](../variable/cmake_mfc_flag)
* [CMAKE\_MODULE\_PATH](../variable/cmake_module_path)
* [CMAKE\_NOT\_USING\_CONFIG\_FLAGS](../variable/cmake_not_using_config_flags)
* [CMAKE\_POLICY\_DEFAULT\_CMP<NNNN>](../variable/cmake_policy_default_cmpnnnn)
* [CMAKE\_POLICY\_WARNING\_CMP<NNNN>](../variable/cmake_policy_warning_cmpnnnn)
* [CMAKE\_PREFIX\_PATH](../variable/cmake_prefix_path)
* [CMAKE\_PROGRAM\_PATH](../variable/cmake_program_path)
* [CMAKE\_PROJECT\_<PROJECT-NAME>\_INCLUDE](../variable/cmake_project_project-name_include)
* [CMAKE\_SKIP\_INSTALL\_ALL\_DEPENDENCY](../variable/cmake_skip_install_all_dependency)
* [CMAKE\_STAGING\_PREFIX](../variable/cmake_staging_prefix)
* [CMAKE\_SUBLIME\_TEXT\_2\_ENV\_SETTINGS](../variable/cmake_sublime_text_2_env_settings)
* [CMAKE\_SUBLIME\_TEXT\_2\_EXCLUDE\_BUILD\_TREE](../variable/cmake_sublime_text_2_exclude_build_tree)
* [CMAKE\_SYSROOT](../variable/cmake_sysroot)
* [CMAKE\_SYSROOT\_COMPILE](../variable/cmake_sysroot_compile)
* [CMAKE\_SYSROOT\_LINK](../variable/cmake_sysroot_link)
* [CMAKE\_SYSTEM\_APPBUNDLE\_PATH](../variable/cmake_system_appbundle_path)
* [CMAKE\_SYSTEM\_FRAMEWORK\_PATH](../variable/cmake_system_framework_path)
* [CMAKE\_SYSTEM\_IGNORE\_PATH](../variable/cmake_system_ignore_path)
* [CMAKE\_SYSTEM\_INCLUDE\_PATH](../variable/cmake_system_include_path)
* [CMAKE\_SYSTEM\_LIBRARY\_PATH](../variable/cmake_system_library_path)
* [CMAKE\_SYSTEM\_PREFIX\_PATH](../variable/cmake_system_prefix_path)
* [CMAKE\_SYSTEM\_PROGRAM\_PATH](../variable/cmake_system_program_path)
* [CMAKE\_USER\_MAKE\_RULES\_OVERRIDE](../variable/cmake_user_make_rules_override)
* [CMAKE\_WARN\_DEPRECATED](../variable/cmake_warn_deprecated)
* [CMAKE\_WARN\_ON\_ABSOLUTE\_INSTALL\_DESTINATION](../variable/cmake_warn_on_absolute_install_destination)
Variables that Describe the System
----------------------------------
* [ANDROID](../variable/android)
* [APPLE](../variable/apple)
* [BORLAND](../variable/borland)
* [CMAKE\_CL\_64](../variable/cmake_cl_64)
* [CMAKE\_COMPILER\_2005](../variable/cmake_compiler_2005)
* [CMAKE\_HOST\_APPLE](../variable/cmake_host_apple)
* [CMAKE\_HOST\_SOLARIS](../variable/cmake_host_solaris)
* [CMAKE\_HOST\_SYSTEM](../variable/cmake_host_system)
* [CMAKE\_HOST\_SYSTEM\_NAME](../variable/cmake_host_system_name)
* [CMAKE\_HOST\_SYSTEM\_PROCESSOR](../variable/cmake_host_system_processor)
* [CMAKE\_HOST\_SYSTEM\_VERSION](../variable/cmake_host_system_version)
* [CMAKE\_HOST\_UNIX](../variable/cmake_host_unix)
* [CMAKE\_HOST\_WIN32](../variable/cmake_host_win32)
* [CMAKE\_LIBRARY\_ARCHITECTURE](../variable/cmake_library_architecture)
* [CMAKE\_LIBRARY\_ARCHITECTURE\_REGEX](../variable/cmake_library_architecture_regex)
* [CMAKE\_OBJECT\_PATH\_MAX](../variable/cmake_object_path_max)
* [CMAKE\_SYSTEM](../variable/cmake_system)
* [CMAKE\_SYSTEM\_NAME](../variable/cmake_system_name)
* [CMAKE\_SYSTEM\_PROCESSOR](../variable/cmake_system_processor)
* [CMAKE\_SYSTEM\_VERSION](../variable/cmake_system_version)
* [CYGWIN](../variable/cygwin)
* [ENV](../variable/env)
* [GHS-MULTI](../variable/ghs-multi)
* [MINGW](../variable/mingw)
* [MSVC](../variable/msvc)
* [MSVC10](../variable/msvc10)
* [MSVC11](../variable/msvc11)
* [MSVC12](../variable/msvc12)
* [MSVC14](../variable/msvc14)
* [MSVC60](../variable/msvc60)
* [MSVC70](../variable/msvc70)
* [MSVC71](../variable/msvc71)
* [MSVC80](../variable/msvc80)
* [MSVC90](../variable/msvc90)
* [MSVC\_IDE](../variable/msvc_ide)
* [MSVC\_VERSION](../variable/msvc_version)
* [UNIX](../variable/unix)
* [WIN32](../variable/win32)
* [WINCE](../variable/wince)
* [WINDOWS\_PHONE](../variable/windows_phone)
* [WINDOWS\_STORE](../variable/windows_store)
* [XCODE](../variable/xcode)
* [XCODE\_VERSION](../variable/xcode_version)
Variables that Control the Build
--------------------------------
* [CMAKE\_ANDROID\_ANT\_ADDITIONAL\_OPTIONS](../variable/cmake_android_ant_additional_options)
* [CMAKE\_ANDROID\_API](../variable/cmake_android_api)
* [CMAKE\_ANDROID\_API\_MIN](../variable/cmake_android_api_min)
* [CMAKE\_ANDROID\_ARCH](../variable/cmake_android_arch)
* [CMAKE\_ANDROID\_ARCH\_ABI](../variable/cmake_android_arch_abi)
* [CMAKE\_ANDROID\_ARM\_MODE](../variable/cmake_android_arm_mode)
* [CMAKE\_ANDROID\_ARM\_NEON](../variable/cmake_android_arm_neon)
* [CMAKE\_ANDROID\_ASSETS\_DIRECTORIES](../variable/cmake_android_assets_directories)
* [CMAKE\_ANDROID\_GUI](../variable/cmake_android_gui)
* [CMAKE\_ANDROID\_JAR\_DEPENDENCIES](../variable/cmake_android_jar_dependencies)
* [CMAKE\_ANDROID\_JAR\_DIRECTORIES](../variable/cmake_android_jar_directories)
* [CMAKE\_ANDROID\_JAVA\_SOURCE\_DIR](../variable/cmake_android_java_source_dir)
* [CMAKE\_ANDROID\_NATIVE\_LIB\_DEPENDENCIES](../variable/cmake_android_native_lib_dependencies)
* [CMAKE\_ANDROID\_NATIVE\_LIB\_DIRECTORIES](../variable/cmake_android_native_lib_directories)
* [CMAKE\_ANDROID\_NDK](../variable/cmake_android_ndk)
* [CMAKE\_ANDROID\_NDK\_DEPRECATED\_HEADERS](../variable/cmake_android_ndk_deprecated_headers)
* [CMAKE\_ANDROID\_NDK\_TOOLCHAIN\_HOST\_TAG](../variable/cmake_android_ndk_toolchain_host_tag)
* [CMAKE\_ANDROID\_NDK\_TOOLCHAIN\_VERSION](../variable/cmake_android_ndk_toolchain_version)
* [CMAKE\_ANDROID\_PROCESS\_MAX](../variable/cmake_android_process_max)
* [CMAKE\_ANDROID\_PROGUARD](../variable/cmake_android_proguard)
* [CMAKE\_ANDROID\_PROGUARD\_CONFIG\_PATH](../variable/cmake_android_proguard_config_path)
* [CMAKE\_ANDROID\_SECURE\_PROPS\_PATH](../variable/cmake_android_secure_props_path)
* [CMAKE\_ANDROID\_SKIP\_ANT\_STEP](../variable/cmake_android_skip_ant_step)
* [CMAKE\_ANDROID\_STANDALONE\_TOOLCHAIN](../variable/cmake_android_standalone_toolchain)
* [CMAKE\_ANDROID\_STL\_TYPE](../variable/cmake_android_stl_type)
* [CMAKE\_ARCHIVE\_OUTPUT\_DIRECTORY](../variable/cmake_archive_output_directory)
* [CMAKE\_ARCHIVE\_OUTPUT\_DIRECTORY\_<CONFIG>](../variable/cmake_archive_output_directory_config)
* [CMAKE\_AUTOMOC](../variable/cmake_automoc)
* [CMAKE\_AUTOMOC\_DEPEND\_FILTERS](../variable/cmake_automoc_depend_filters)
* [CMAKE\_AUTOMOC\_MOC\_OPTIONS](../variable/cmake_automoc_moc_options)
* [CMAKE\_AUTORCC](../variable/cmake_autorcc)
* [CMAKE\_AUTORCC\_OPTIONS](../variable/cmake_autorcc_options)
* [CMAKE\_AUTOUIC](../variable/cmake_autouic)
* [CMAKE\_AUTOUIC\_OPTIONS](../variable/cmake_autouic_options)
* [CMAKE\_AUTOUIC\_SEARCH\_PATHS](../variable/cmake_autouic_search_paths)
* [CMAKE\_BUILD\_RPATH](../variable/cmake_build_rpath)
* [CMAKE\_BUILD\_WITH\_INSTALL\_NAME\_DIR](../variable/cmake_build_with_install_name_dir)
* [CMAKE\_BUILD\_WITH\_INSTALL\_RPATH](../variable/cmake_build_with_install_rpath)
* [CMAKE\_COMPILE\_PDB\_OUTPUT\_DIRECTORY](../variable/cmake_compile_pdb_output_directory)
* [CMAKE\_COMPILE\_PDB\_OUTPUT\_DIRECTORY\_<CONFIG>](../variable/cmake_compile_pdb_output_directory_config)
* [CMAKE\_<CONFIG>\_POSTFIX](../variable/cmake_config_postfix)
* [CMAKE\_DEBUG\_POSTFIX](../variable/cmake_debug_postfix)
* [CMAKE\_ENABLE\_EXPORTS](../variable/cmake_enable_exports)
* [CMAKE\_EXE\_LINKER\_FLAGS](../variable/cmake_exe_linker_flags)
* [CMAKE\_EXE\_LINKER\_FLAGS\_<CONFIG>](../variable/cmake_exe_linker_flags_config)
* [CMAKE\_EXE\_LINKER\_FLAGS\_<CONFIG>\_INIT](../variable/cmake_exe_linker_flags_config_init)
* [CMAKE\_EXE\_LINKER\_FLAGS\_INIT](../variable/cmake_exe_linker_flags_init)
* [CMAKE\_Fortran\_FORMAT](../variable/cmake_fortran_format)
* [CMAKE\_Fortran\_MODULE\_DIRECTORY](../variable/cmake_fortran_module_directory)
* [CMAKE\_GNUtoMS](../variable/cmake_gnutoms)
* [CMAKE\_INCLUDE\_CURRENT\_DIR](../variable/cmake_include_current_dir)
* [CMAKE\_INCLUDE\_CURRENT\_DIR\_IN\_INTERFACE](../variable/cmake_include_current_dir_in_interface)
* [CMAKE\_INSTALL\_NAME\_DIR](../variable/cmake_install_name_dir)
* [CMAKE\_INSTALL\_RPATH](../variable/cmake_install_rpath)
* [CMAKE\_INSTALL\_RPATH\_USE\_LINK\_PATH](../variable/cmake_install_rpath_use_link_path)
* [CMAKE\_INTERPROCEDURAL\_OPTIMIZATION](../variable/cmake_interprocedural_optimization)
* [CMAKE\_INTERPROCEDURAL\_OPTIMIZATION\_<CONFIG>](../variable/cmake_interprocedural_optimization_config)
* [CMAKE\_IOS\_INSTALL\_COMBINED](../variable/cmake_ios_install_combined)
* [CMAKE\_<LANG>\_CLANG\_TIDY](../variable/cmake_lang_clang_tidy)
* [CMAKE\_<LANG>\_COMPILER\_LAUNCHER](../variable/cmake_lang_compiler_launcher)
* [CMAKE\_<LANG>\_CPPLINT](../variable/cmake_lang_cpplint)
* [CMAKE\_<LANG>\_INCLUDE\_WHAT\_YOU\_USE](../variable/cmake_lang_include_what_you_use)
* [CMAKE\_<LANG>\_VISIBILITY\_PRESET](../variable/cmake_lang_visibility_preset)
* [CMAKE\_LIBRARY\_OUTPUT\_DIRECTORY](../variable/cmake_library_output_directory)
* [CMAKE\_LIBRARY\_OUTPUT\_DIRECTORY\_<CONFIG>](../variable/cmake_library_output_directory_config)
* [CMAKE\_LIBRARY\_PATH\_FLAG](../variable/cmake_library_path_flag)
* [CMAKE\_LINK\_DEF\_FILE\_FLAG](../variable/cmake_link_def_file_flag)
* [CMAKE\_LINK\_DEPENDS\_NO\_SHARED](../variable/cmake_link_depends_no_shared)
* [CMAKE\_LINK\_INTERFACE\_LIBRARIES](../variable/cmake_link_interface_libraries)
* [CMAKE\_LINK\_LIBRARY\_FILE\_FLAG](../variable/cmake_link_library_file_flag)
* [CMAKE\_LINK\_LIBRARY\_FLAG](../variable/cmake_link_library_flag)
* [CMAKE\_LINK\_WHAT\_YOU\_USE](../variable/cmake_link_what_you_use)
* [CMAKE\_MACOSX\_BUNDLE](../variable/cmake_macosx_bundle)
* [CMAKE\_MACOSX\_RPATH](../variable/cmake_macosx_rpath)
* [CMAKE\_MAP\_IMPORTED\_CONFIG\_<CONFIG>](../variable/cmake_map_imported_config_config)
* [CMAKE\_MODULE\_LINKER\_FLAGS](../variable/cmake_module_linker_flags)
* [CMAKE\_MODULE\_LINKER\_FLAGS\_<CONFIG>](../variable/cmake_module_linker_flags_config)
* [CMAKE\_MODULE\_LINKER\_FLAGS\_<CONFIG>\_INIT](../variable/cmake_module_linker_flags_config_init)
* [CMAKE\_MODULE\_LINKER\_FLAGS\_INIT](../variable/cmake_module_linker_flags_init)
* [CMAKE\_NINJA\_OUTPUT\_PATH\_PREFIX](../variable/cmake_ninja_output_path_prefix)
* [CMAKE\_NO\_BUILTIN\_CHRPATH](../variable/cmake_no_builtin_chrpath)
* [CMAKE\_NO\_SYSTEM\_FROM\_IMPORTED](../variable/cmake_no_system_from_imported)
* [CMAKE\_OSX\_ARCHITECTURES](../variable/cmake_osx_architectures)
* [CMAKE\_OSX\_DEPLOYMENT\_TARGET](../variable/cmake_osx_deployment_target)
* [CMAKE\_OSX\_SYSROOT](../variable/cmake_osx_sysroot)
* [CMAKE\_PDB\_OUTPUT\_DIRECTORY](../variable/cmake_pdb_output_directory)
* [CMAKE\_PDB\_OUTPUT\_DIRECTORY\_<CONFIG>](../variable/cmake_pdb_output_directory_config)
* [CMAKE\_POSITION\_INDEPENDENT\_CODE](../variable/cmake_position_independent_code)
* [CMAKE\_RUNTIME\_OUTPUT\_DIRECTORY](../variable/cmake_runtime_output_directory)
* [CMAKE\_RUNTIME\_OUTPUT\_DIRECTORY\_<CONFIG>](../variable/cmake_runtime_output_directory_config)
* [CMAKE\_SHARED\_LINKER\_FLAGS](../variable/cmake_shared_linker_flags)
* [CMAKE\_SHARED\_LINKER\_FLAGS\_<CONFIG>](../variable/cmake_shared_linker_flags_config)
* [CMAKE\_SHARED\_LINKER\_FLAGS\_<CONFIG>\_INIT](../variable/cmake_shared_linker_flags_config_init)
* [CMAKE\_SHARED\_LINKER\_FLAGS\_INIT](../variable/cmake_shared_linker_flags_init)
* [CMAKE\_SKIP\_BUILD\_RPATH](../variable/cmake_skip_build_rpath)
* [CMAKE\_SKIP\_INSTALL\_RPATH](../variable/cmake_skip_install_rpath)
* [CMAKE\_STATIC\_LINKER\_FLAGS](../variable/cmake_static_linker_flags)
* [CMAKE\_STATIC\_LINKER\_FLAGS\_<CONFIG>](../variable/cmake_static_linker_flags_config)
* [CMAKE\_STATIC\_LINKER\_FLAGS\_<CONFIG>\_INIT](../variable/cmake_static_linker_flags_config_init)
* [CMAKE\_STATIC\_LINKER\_FLAGS\_INIT](../variable/cmake_static_linker_flags_init)
* [CMAKE\_TRY\_COMPILE\_CONFIGURATION](../variable/cmake_try_compile_configuration)
* [CMAKE\_TRY\_COMPILE\_PLATFORM\_VARIABLES](../variable/cmake_try_compile_platform_variables)
* [CMAKE\_TRY\_COMPILE\_TARGET\_TYPE](../variable/cmake_try_compile_target_type)
* [CMAKE\_USE\_RELATIVE\_PATHS](../variable/cmake_use_relative_paths)
* [CMAKE\_VISIBILITY\_INLINES\_HIDDEN](../variable/cmake_visibility_inlines_hidden)
* [CMAKE\_VS\_INCLUDE\_INSTALL\_TO\_DEFAULT\_BUILD](../variable/cmake_vs_include_install_to_default_build)
* [CMAKE\_VS\_INCLUDE\_PACKAGE\_TO\_DEFAULT\_BUILD](../variable/cmake_vs_include_package_to_default_build)
* [CMAKE\_WIN32\_EXECUTABLE](../variable/cmake_win32_executable)
* [CMAKE\_WINDOWS\_EXPORT\_ALL\_SYMBOLS](../variable/cmake_windows_export_all_symbols)
* [CMAKE\_XCODE\_ATTRIBUTE\_<an-attribute>](../variable/cmake_xcode_attribute_an-attribute)
* [EXECUTABLE\_OUTPUT\_PATH](../variable/executable_output_path)
* [LIBRARY\_OUTPUT\_PATH](../variable/library_output_path)
Variables for Languages
-----------------------
* [CMAKE\_COMPILER\_IS\_GNUCC](../variable/cmake_compiler_is_gnucc)
* [CMAKE\_COMPILER\_IS\_GNUCXX](../variable/cmake_compiler_is_gnucxx)
* [CMAKE\_COMPILER\_IS\_GNUG77](../variable/cmake_compiler_is_gnug77)
* [CMAKE\_CUDA\_EXTENSIONS](../variable/cmake_cuda_extensions)
* [CMAKE\_CUDA\_STANDARD](../variable/cmake_cuda_standard)
* [CMAKE\_CUDA\_STANDARD\_REQUIRED](../variable/cmake_cuda_standard_required)
* [CMAKE\_CUDA\_TOOLKIT\_INCLUDE\_DIRECTORIES](../variable/cmake_cuda_toolkit_include_directories)
* [CMAKE\_CXX\_COMPILE\_FEATURES](../variable/cmake_cxx_compile_features)
* [CMAKE\_CXX\_EXTENSIONS](../variable/cmake_cxx_extensions)
* [CMAKE\_CXX\_STANDARD](../variable/cmake_cxx_standard)
* [CMAKE\_CXX\_STANDARD\_REQUIRED](../variable/cmake_cxx_standard_required)
* [CMAKE\_C\_COMPILE\_FEATURES](../variable/cmake_c_compile_features)
* [CMAKE\_C\_EXTENSIONS](../variable/cmake_c_extensions)
* [CMAKE\_C\_STANDARD](../variable/cmake_c_standard)
* [CMAKE\_C\_STANDARD\_REQUIRED](../variable/cmake_c_standard_required)
* [CMAKE\_Fortran\_MODDIR\_DEFAULT](../variable/cmake_fortran_moddir_default)
* [CMAKE\_Fortran\_MODDIR\_FLAG](../variable/cmake_fortran_moddir_flag)
* [CMAKE\_Fortran\_MODOUT\_FLAG](../variable/cmake_fortran_modout_flag)
* [CMAKE\_INTERNAL\_PLATFORM\_ABI](../variable/cmake_internal_platform_abi)
* [CMAKE\_<LANG>\_ANDROID\_TOOLCHAIN\_MACHINE](../variable/cmake_lang_android_toolchain_machine)
* [CMAKE\_<LANG>\_ANDROID\_TOOLCHAIN\_PREFIX](../variable/cmake_lang_android_toolchain_prefix)
* [CMAKE\_<LANG>\_ANDROID\_TOOLCHAIN\_SUFFIX](../variable/cmake_lang_android_toolchain_suffix)
* [CMAKE\_<LANG>\_ARCHIVE\_APPEND](../variable/cmake_lang_archive_append)
* [CMAKE\_<LANG>\_ARCHIVE\_CREATE](../variable/cmake_lang_archive_create)
* [CMAKE\_<LANG>\_ARCHIVE\_FINISH](../variable/cmake_lang_archive_finish)
* [CMAKE\_<LANG>\_COMPILER](../variable/cmake_lang_compiler)
* [CMAKE\_<LANG>\_COMPILER\_ABI](../variable/cmake_lang_compiler_abi)
* [CMAKE\_<LANG>\_COMPILER\_EXTERNAL\_TOOLCHAIN](../variable/cmake_lang_compiler_external_toolchain)
* [CMAKE\_<LANG>\_COMPILER\_ID](../variable/cmake_lang_compiler_id)
* [CMAKE\_<LANG>\_COMPILER\_LOADED](../variable/cmake_lang_compiler_loaded)
* [CMAKE\_<LANG>\_COMPILER\_TARGET](../variable/cmake_lang_compiler_target)
* [CMAKE\_<LANG>\_COMPILER\_VERSION](../variable/cmake_lang_compiler_version)
* [CMAKE\_<LANG>\_COMPILE\_OBJECT](../variable/cmake_lang_compile_object)
* [CMAKE\_<LANG>\_CREATE\_SHARED\_LIBRARY](../variable/cmake_lang_create_shared_library)
* [CMAKE\_<LANG>\_CREATE\_SHARED\_MODULE](../variable/cmake_lang_create_shared_module)
* [CMAKE\_<LANG>\_CREATE\_STATIC\_LIBRARY](../variable/cmake_lang_create_static_library)
* [CMAKE\_<LANG>\_FLAGS](../variable/cmake_lang_flags)
* [CMAKE\_<LANG>\_FLAGS\_DEBUG](../variable/cmake_lang_flags_debug)
* [CMAKE\_<LANG>\_FLAGS\_DEBUG\_INIT](../variable/cmake_lang_flags_debug_init)
* [CMAKE\_<LANG>\_FLAGS\_INIT](../variable/cmake_lang_flags_init)
* [CMAKE\_<LANG>\_FLAGS\_MINSIZEREL](../variable/cmake_lang_flags_minsizerel)
* [CMAKE\_<LANG>\_FLAGS\_MINSIZEREL\_INIT](../variable/cmake_lang_flags_minsizerel_init)
* [CMAKE\_<LANG>\_FLAGS\_RELEASE](../variable/cmake_lang_flags_release)
* [CMAKE\_<LANG>\_FLAGS\_RELEASE\_INIT](../variable/cmake_lang_flags_release_init)
* [CMAKE\_<LANG>\_FLAGS\_RELWITHDEBINFO](../variable/cmake_lang_flags_relwithdebinfo)
* [CMAKE\_<LANG>\_FLAGS\_RELWITHDEBINFO\_INIT](../variable/cmake_lang_flags_relwithdebinfo_init)
* [CMAKE\_<LANG>\_GHS\_KERNEL\_FLAGS\_DEBUG](../variable/cmake_lang_ghs_kernel_flags_debug)
* [CMAKE\_<LANG>\_GHS\_KERNEL\_FLAGS\_MINSIZEREL](../variable/cmake_lang_ghs_kernel_flags_minsizerel)
* [CMAKE\_<LANG>\_GHS\_KERNEL\_FLAGS\_RELEASE](../variable/cmake_lang_ghs_kernel_flags_release)
* [CMAKE\_<LANG>\_GHS\_KERNEL\_FLAGS\_RELWITHDEBINFO](../variable/cmake_lang_ghs_kernel_flags_relwithdebinfo)
* [CMAKE\_<LANG>\_IGNORE\_EXTENSIONS](../variable/cmake_lang_ignore_extensions)
* [CMAKE\_<LANG>\_IMPLICIT\_INCLUDE\_DIRECTORIES](../variable/cmake_lang_implicit_include_directories)
* [CMAKE\_<LANG>\_IMPLICIT\_LINK\_DIRECTORIES](../variable/cmake_lang_implicit_link_directories)
* [CMAKE\_<LANG>\_IMPLICIT\_LINK\_FRAMEWORK\_DIRECTORIES](../variable/cmake_lang_implicit_link_framework_directories)
* [CMAKE\_<LANG>\_IMPLICIT\_LINK\_LIBRARIES](../variable/cmake_lang_implicit_link_libraries)
* [CMAKE\_<LANG>\_LIBRARY\_ARCHITECTURE](../variable/cmake_lang_library_architecture)
* [CMAKE\_<LANG>\_LINKER\_PREFERENCE](../variable/cmake_lang_linker_preference)
* [CMAKE\_<LANG>\_LINKER\_PREFERENCE\_PROPAGATES](../variable/cmake_lang_linker_preference_propagates)
* [CMAKE\_<LANG>\_LINK\_EXECUTABLE](../variable/cmake_lang_link_executable)
* [CMAKE\_<LANG>\_OUTPUT\_EXTENSION](../variable/cmake_lang_output_extension)
* [CMAKE\_<LANG>\_PLATFORM\_ID](../variable/cmake_lang_platform_id)
* [CMAKE\_<LANG>\_SIMULATE\_ID](../variable/cmake_lang_simulate_id)
* [CMAKE\_<LANG>\_SIMULATE\_VERSION](../variable/cmake_lang_simulate_version)
* [CMAKE\_<LANG>\_SIZEOF\_DATA\_PTR](../variable/cmake_lang_sizeof_data_ptr)
* [CMAKE\_<LANG>\_SOURCE\_FILE\_EXTENSIONS](../variable/cmake_lang_source_file_extensions)
* [CMAKE\_<LANG>\_STANDARD\_INCLUDE\_DIRECTORIES](../variable/cmake_lang_standard_include_directories)
* [CMAKE\_<LANG>\_STANDARD\_LIBRARIES](../variable/cmake_lang_standard_libraries)
* [CMAKE\_Swift\_LANGUAGE\_VERSION](../variable/cmake_swift_language_version)
* [CMAKE\_USER\_MAKE\_RULES\_OVERRIDE\_<LANG>](../variable/cmake_user_make_rules_override_lang)
Variables for CTest
-------------------
* [CTEST\_BINARY\_DIRECTORY](../variable/ctest_binary_directory)
* [CTEST\_BUILD\_COMMAND](../variable/ctest_build_command)
* [CTEST\_BUILD\_NAME](../variable/ctest_build_name)
* [CTEST\_BZR\_COMMAND](../variable/ctest_bzr_command)
* [CTEST\_BZR\_UPDATE\_OPTIONS](../variable/ctest_bzr_update_options)
* [CTEST\_CHANGE\_ID](../variable/ctest_change_id)
* [CTEST\_CHECKOUT\_COMMAND](../variable/ctest_checkout_command)
* [CTEST\_CONFIGURATION\_TYPE](../variable/ctest_configuration_type)
* [CTEST\_CONFIGURE\_COMMAND](../variable/ctest_configure_command)
* [CTEST\_COVERAGE\_COMMAND](../variable/ctest_coverage_command)
* [CTEST\_COVERAGE\_EXTRA\_FLAGS](../variable/ctest_coverage_extra_flags)
* [CTEST\_CURL\_OPTIONS](../variable/ctest_curl_options)
* [CTEST\_CUSTOM\_COVERAGE\_EXCLUDE](../variable/ctest_custom_coverage_exclude)
* [CTEST\_CUSTOM\_ERROR\_EXCEPTION](../variable/ctest_custom_error_exception)
* [CTEST\_CUSTOM\_ERROR\_MATCH](../variable/ctest_custom_error_match)
* [CTEST\_CUSTOM\_ERROR\_POST\_CONTEXT](../variable/ctest_custom_error_post_context)
* [CTEST\_CUSTOM\_ERROR\_PRE\_CONTEXT](../variable/ctest_custom_error_pre_context)
* [CTEST\_CUSTOM\_MAXIMUM\_FAILED\_TEST\_OUTPUT\_SIZE](../variable/ctest_custom_maximum_failed_test_output_size)
* [CTEST\_CUSTOM\_MAXIMUM\_NUMBER\_OF\_ERRORS](../variable/ctest_custom_maximum_number_of_errors)
* [CTEST\_CUSTOM\_MAXIMUM\_NUMBER\_OF\_WARNINGS](../variable/ctest_custom_maximum_number_of_warnings)
* [CTEST\_CUSTOM\_MAXIMUM\_PASSED\_TEST\_OUTPUT\_SIZE](../variable/ctest_custom_maximum_passed_test_output_size)
* [CTEST\_CUSTOM\_MEMCHECK\_IGNORE](../variable/ctest_custom_memcheck_ignore)
* [CTEST\_CUSTOM\_POST\_MEMCHECK](../variable/ctest_custom_post_memcheck)
* [CTEST\_CUSTOM\_POST\_TEST](../variable/ctest_custom_post_test)
* [CTEST\_CUSTOM\_PRE\_MEMCHECK](../variable/ctest_custom_pre_memcheck)
* [CTEST\_CUSTOM\_PRE\_TEST](../variable/ctest_custom_pre_test)
* [CTEST\_CUSTOM\_TEST\_IGNORE](../variable/ctest_custom_test_ignore)
* [CTEST\_CUSTOM\_WARNING\_EXCEPTION](../variable/ctest_custom_warning_exception)
* [CTEST\_CUSTOM\_WARNING\_MATCH](../variable/ctest_custom_warning_match)
* [CTEST\_CVS\_CHECKOUT](../variable/ctest_cvs_checkout)
* [CTEST\_CVS\_COMMAND](../variable/ctest_cvs_command)
* [CTEST\_CVS\_UPDATE\_OPTIONS](../variable/ctest_cvs_update_options)
* [CTEST\_DROP\_LOCATION](../variable/ctest_drop_location)
* [CTEST\_DROP\_METHOD](../variable/ctest_drop_method)
* [CTEST\_DROP\_SITE](../variable/ctest_drop_site)
* [CTEST\_DROP\_SITE\_CDASH](../variable/ctest_drop_site_cdash)
* [CTEST\_DROP\_SITE\_PASSWORD](../variable/ctest_drop_site_password)
* [CTEST\_DROP\_SITE\_USER](../variable/ctest_drop_site_user)
* [CTEST\_EXTRA\_COVERAGE\_GLOB](../variable/ctest_extra_coverage_glob)
* [CTEST\_GIT\_COMMAND](../variable/ctest_git_command)
* [CTEST\_GIT\_INIT\_SUBMODULES](../variable/ctest_git_init_submodules)
* [CTEST\_GIT\_UPDATE\_CUSTOM](../variable/ctest_git_update_custom)
* [CTEST\_GIT\_UPDATE\_OPTIONS](../variable/ctest_git_update_options)
* [CTEST\_HG\_COMMAND](../variable/ctest_hg_command)
* [CTEST\_HG\_UPDATE\_OPTIONS](../variable/ctest_hg_update_options)
* [CTEST\_MEMORYCHECK\_COMMAND](../variable/ctest_memorycheck_command)
* [CTEST\_MEMORYCHECK\_COMMAND\_OPTIONS](../variable/ctest_memorycheck_command_options)
* [CTEST\_MEMORYCHECK\_SANITIZER\_OPTIONS](../variable/ctest_memorycheck_sanitizer_options)
* [CTEST\_MEMORYCHECK\_SUPPRESSIONS\_FILE](../variable/ctest_memorycheck_suppressions_file)
* [CTEST\_MEMORYCHECK\_TYPE](../variable/ctest_memorycheck_type)
* [CTEST\_NIGHTLY\_START\_TIME](../variable/ctest_nightly_start_time)
* [CTEST\_P4\_CLIENT](../variable/ctest_p4_client)
* [CTEST\_P4\_COMMAND](../variable/ctest_p4_command)
* [CTEST\_P4\_OPTIONS](../variable/ctest_p4_options)
* [CTEST\_P4\_UPDATE\_OPTIONS](../variable/ctest_p4_update_options)
* [CTEST\_SCP\_COMMAND](../variable/ctest_scp_command)
* [CTEST\_SITE](../variable/ctest_site)
* [CTEST\_SOURCE\_DIRECTORY](../variable/ctest_source_directory)
* [CTEST\_SVN\_COMMAND](../variable/ctest_svn_command)
* [CTEST\_SVN\_OPTIONS](../variable/ctest_svn_options)
* [CTEST\_SVN\_UPDATE\_OPTIONS](../variable/ctest_svn_update_options)
* [CTEST\_TEST\_LOAD](../variable/ctest_test_load)
* [CTEST\_TEST\_TIMEOUT](../variable/ctest_test_timeout)
* [CTEST\_TRIGGER\_SITE](../variable/ctest_trigger_site)
* [CTEST\_UPDATE\_COMMAND](../variable/ctest_update_command)
* [CTEST\_UPDATE\_OPTIONS](../variable/ctest_update_options)
* [CTEST\_UPDATE\_VERSION\_ONLY](../variable/ctest_update_version_only)
* [CTEST\_USE\_LAUNCHERS](../variable/ctest_use_launchers)
Variables for CPack
-------------------
* [CPACK\_ABSOLUTE\_DESTINATION\_FILES](../variable/cpack_absolute_destination_files)
* [CPACK\_COMPONENT\_INCLUDE\_TOPLEVEL\_DIRECTORY](../variable/cpack_component_include_toplevel_directory)
* [CPACK\_ERROR\_ON\_ABSOLUTE\_INSTALL\_DESTINATION](../variable/cpack_error_on_absolute_install_destination)
* [CPACK\_INCLUDE\_TOPLEVEL\_DIRECTORY](../variable/cpack_include_toplevel_directory)
* [CPACK\_INSTALL\_SCRIPT](../variable/cpack_install_script)
* [CPACK\_PACKAGING\_INSTALL\_PREFIX](../variable/cpack_packaging_install_prefix)
* [CPACK\_SET\_DESTDIR](../variable/cpack_set_destdir)
* [CPACK\_WARN\_ON\_ABSOLUTE\_INSTALL\_DESTINATION](../variable/cpack_warn_on_absolute_install_destination)
| programming_docs |
cmake cmake-generator-expressions(7) cmake-generator-expressions(7)
==============================
* [Introduction](#introduction)
* [Logical Expressions](#logical-expressions)
* [Informational Expressions](#informational-expressions)
* [Output Expressions](#output-expressions)
Introduction
------------
Generator expressions are evaluated during build system generation to produce information specific to each build configuration.
Generator expressions are allowed in the context of many target properties, such as [`LINK_LIBRARIES`](../prop_tgt/link_libraries#prop_tgt:LINK_LIBRARIES "LINK_LIBRARIES"), [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES"), [`COMPILE_DEFINITIONS`](../prop_tgt/compile_definitions#prop_tgt:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") and others. They may also be used when using commands to populate those properties, such as [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries"), [`target_include_directories()`](../command/target_include_directories#command:target_include_directories "target_include_directories"), [`target_compile_definitions()`](../command/target_compile_definitions#command:target_compile_definitions "target_compile_definitions") and others.
This means that they enable conditional linking, conditional definitions used when compiling, and conditional include directories and more. The conditions may be based on the build configuration, target properties, platform information or any other queryable information.
Logical Expressions
-------------------
Logical expressions are used to create conditional output. The basic expressions are the `0` and `1` expressions. Because other logical expressions evaluate to either `0` or `1`, they can be composed to create conditional output:
```
$<$<CONFIG:Debug>:DEBUG_MODE>
```
expands to `DEBUG_MODE` when the `Debug` configuration is used, and otherwise expands to nothing.
Available logical expressions are:
`$<BOOL:...>`
`1` if the `...` is true, else `0`
`$<AND:?[,?]...>`
`1` if all `?` are `1`, else `0`
The `?` must always be either `0` or `1` in boolean expressions.
`$<OR:?[,?]...>`
`0` if all `?` are `0`, else `1`
`$<NOT:?>`
`0` if `?` is `1`, else `1`
`$<IF:?,true-value...,false-value...>``
`true-value...` if `?` is `1`, `false-value...` if `?` is `0`
`$<STREQUAL:a,b>`
`1` if `a` is STREQUAL `b`, else `0`
`$<EQUAL:a,b>`
`1` if `a` is EQUAL `b` in a numeric comparison, else `0`
`$<CONFIG:cfg>`
`1` if config is `cfg`, else `0`. This is a case-insensitive comparison. The mapping in [`MAP_IMPORTED_CONFIG_<CONFIG>`](# "MAP_IMPORTED_CONFIG_<CONFIG>") is also considered by this expression when it is evaluated on a property on an [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target.
`$<PLATFORM_ID:comp>`
`1` if the CMake-id of the platform matches `comp`, otherwise `0`.
`$<C_COMPILER_ID:comp>`
`1` if the CMake-id of the C compiler matches `comp`, otherwise `0`.
`$<CXX_COMPILER_ID:comp>`
`1` if the CMake-id of the CXX compiler matches `comp`, otherwise `0`.
`$<VERSION_LESS:v1,v2>`
`1` if `v1` is a version less than `v2`, else `0`.
`$<VERSION_GREATER:v1,v2>`
`1` if `v1` is a version greater than `v2`, else `0`.
`$<VERSION_EQUAL:v1,v2>`
`1` if `v1` is the same version as `v2`, else `0`.
`$<VERSION_LESS_EQUAL:v1,v2>`
`1` if `v1` is a version less than or equal to `v2`, else `0`.
`$<VERSION_GREATER_EQUAL:v1,v2>`
`1` if `v1` is a version greater than or equal to `v2`, else `0`.
`$<C_COMPILER_VERSION:ver>`
`1` if the version of the C compiler matches `ver`, otherwise `0`.
`$<CXX_COMPILER_VERSION:ver>`
`1` if the version of the CXX compiler matches `ver`, otherwise `0`.
`$<TARGET_POLICY:pol>`
`1` if the policy `pol` was NEW when the ‘head’ target was created, else `0`. If the policy was not set, the warning message for the policy will be emitted. This generator expression only works for a subset of policies.
`$<COMPILE_FEATURES:feature[,feature]...>`
`1` if all of the `feature` features are available for the ‘head’ target, and `0` otherwise. If this expression is used while evaluating the link implementation of a target and if any dependency transitively increases the required [`C_STANDARD`](../prop_tgt/c_standard#prop_tgt:C_STANDARD "C_STANDARD") or [`CXX_STANDARD`](../prop_tgt/cxx_standard#prop_tgt:CXX_STANDARD "CXX_STANDARD") for the ‘head’ target, an error is reported. See the [`cmake-compile-features(7)`](cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
`$<COMPILE_LANGUAGE:lang>`
`1` when the language used for compilation unit matches `lang`, otherwise `0`. This expression used to specify compile options for source files of a particular language in a target. For example, to specify the use of the `-fno-exceptions` compile option (compiler id checks elided):
```
add_executable(myapp main.cpp foo.c bar.cpp)
target_compile_options(myapp
PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-fno-exceptions>
)
```
This generator expression has limited use because it is not possible to use it with the Visual Studio generators. Portable buildsystems would not use this expression, and would create separate libraries for each source file language instead:
```
add_library(myapp_c foo.c)
add_library(myapp_cxx bar.cpp)
target_compile_options(myapp_cxx PUBLIC -fno-exceptions)
add_executable(myapp main.cpp)
target_link_libraries(myapp myapp_c myapp_cxx)
```
The `Makefile` and `Ninja` based generators can also use this expression to specify compile-language specific compile definitions and include directories:
```
add_executable(myapp main.cpp foo.c bar.cpp)
target_compile_definitions(myapp
PRIVATE $<$<COMPILE_LANGUAGE:CXX>:COMPILING_CXX>
)
target_include_directories(myapp
PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/opt/foo/cxx_headers>
)
```
Informational Expressions
-------------------------
These expressions expand to some information. The information may be used directly, eg:
```
include_directories(/usr/include/$<CXX_COMPILER_ID>/)
```
expands to `/usr/include/GNU/` or `/usr/include/Clang/` etc, depending on the Id of the compiler.
These expressions may also may be combined with logical expressions:
```
$<$<VERSION_LESS:$<CXX_COMPILER_VERSION>,4.2.0>:OLD_COMPILER>
```
expands to `OLD_COMPILER` if the [`CMAKE_CXX_COMPILER_VERSION`](# "CMAKE_<LANG>_COMPILER_VERSION") is less than 4.2.0.
Available informational expressions are:
`$<CONFIGURATION>` Configuration name. Deprecated. Use `CONFIG` instead.
`$<CONFIG>` Configuration name
`$<PLATFORM_ID>` The CMake-id of the platform. See also the [`CMAKE_SYSTEM_NAME`](../variable/cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME") variable.
`$<C_COMPILER_ID>` The CMake-id of the C compiler used. See also the [`CMAKE_<LANG>_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") variable.
`$<CXX_COMPILER_ID>` The CMake-id of the CXX compiler used. See also the [`CMAKE_<LANG>_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") variable.
`$<C_COMPILER_VERSION>` The version of the C compiler used. See also the [`CMAKE_<LANG>_COMPILER_VERSION`](# "CMAKE_<LANG>_COMPILER_VERSION") variable.
`$<CXX_COMPILER_VERSION>` The version of the CXX compiler used. See also the [`CMAKE_<LANG>_COMPILER_VERSION`](# "CMAKE_<LANG>_COMPILER_VERSION") variable.
`$<TARGET_FILE:tgt>` Full path to main file (.exe, .so.1.2, .a) where `tgt` is the name of a target.
`$<TARGET_FILE_NAME:tgt>` Name of main file (.exe, .so.1.2, .a).
`$<TARGET_FILE_DIR:tgt>` Directory of main file (.exe, .so.1.2, .a).
`$<TARGET_LINKER_FILE:tgt>` File used to link (.a, .lib, .so) where `tgt` is the name of a target.
`$<TARGET_LINKER_FILE_NAME:tgt>` Name of file used to link (.a, .lib, .so).
`$<TARGET_LINKER_FILE_DIR:tgt>` Directory of file used to link (.a, .lib, .so).
`$<TARGET_SONAME_FILE:tgt>` File with soname (.so.3) where `tgt` is the name of a target.
`$<TARGET_SONAME_FILE_NAME:tgt>` Name of file with soname (.so.3).
`$<TARGET_SONAME_FILE_DIR:tgt>` Directory of with soname (.so.3).
`$<TARGET_PDB_FILE:tgt>`
Full path to the linker generated program database file (.pdb) where `tgt` is the name of a target.
See also the [`PDB_NAME`](../prop_tgt/pdb_name#prop_tgt:PDB_NAME "PDB_NAME") and [`PDB_OUTPUT_DIRECTORY`](../prop_tgt/pdb_output_directory#prop_tgt:PDB_OUTPUT_DIRECTORY "PDB_OUTPUT_DIRECTORY") target properties and their configuration specific variants [`PDB_NAME_<CONFIG>`](# "PDB_NAME_<CONFIG>") and [`PDB_OUTPUT_DIRECTORY_<CONFIG>`](# "PDB_OUTPUT_DIRECTORY_<CONFIG>").
`$<TARGET_PDB_FILE_NAME:tgt>` Name of the linker generated program database file (.pdb).
`$<TARGET_PDB_FILE_DIR:tgt>` Directory of the linker generated program database file (.pdb).
`$<TARGET_BUNDLE_DIR:tgt>` Full path to the bundle directory (`my.app`, `my.framework`, or `my.bundle`) where `tgt` is the name of a target.
`$<TARGET_BUNDLE_CONTENT_DIR:tgt>` Full path to the bundle content directory where `tgt` is the name of a target. For the macOS SDK it leads to `my.app/Contents`, `my.framework`, or `my.bundle/Contents`. For all other SDKs (e.g. iOS) it leads to `my.app`, `my.framework`, or `my.bundle` due to the flat bundle structure.
`$<TARGET_PROPERTY:tgt,prop>`
Value of the property `prop` on the target `tgt`.
Note that `tgt` is not added as a dependency of the target this expression is evaluated on.
`$<TARGET_PROPERTY:prop>` Value of the property `prop` on the target on which the generator expression is evaluated.
`$<INSTALL_PREFIX>` Content of the install prefix when the target is exported via [`install(EXPORT)`](../command/install#command:install "install") and empty otherwise.
`$<COMPILE_LANGUAGE>` The compile language of source files when evaluating compile options. See the unary version for notes about portability of this generator expression. Output Expressions
------------------
These expressions generate output, in some cases depending on an input. These expressions may be combined with other expressions for information or logical comparison:
```
-I$<JOIN:$<TARGET_PROPERTY:INCLUDE_DIRECTORIES>, -I>
```
generates a string of the entries in the [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES") target property with each entry preceded by `-I`. Note that a more-complete use in this situation would require first checking if the INCLUDE\_DIRECTORIES property is non-empty:
```
$<$<BOOL:${prop}>:-I$<JOIN:${prop}, -I>>
```
where `${prop}` refers to a helper variable:
```
set(prop "$<TARGET_PROPERTY:INCLUDE_DIRECTORIES>")
```
Available output expressions are:
`$<0:...>` Empty string (ignores `...`)
`$<1:...>` Content of `...`
`$<JOIN:list,...>` Joins the list with the content of `...`
`$<ANGLE-R>` A literal `>`. Used to compare strings which contain a `>` for example.
`$<COMMA>` A literal `,`. Used to compare strings which contain a `,` for example.
`$<SEMICOLON>` A literal `;`. Used to prevent list expansion on an argument with `;`.
`$<TARGET_NAME:...>` Marks `...` as being the name of a target. This is required if exporting targets to multiple dependent export sets. The `...` must be a literal name of a target- it may not contain generator expressions.
`$<LINK_ONLY:...>` Content of `...` except when evaluated in a link interface while propagating [Transitive Usage Requirements](cmake-buildsystem.7#target-usage-requirements), in which case it is the empty string. Intended for use only in an [`INTERFACE_LINK_LIBRARIES`](../prop_tgt/interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES") target property, perhaps via the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command, to specify private link dependencies without other usage requirements.
`$<INSTALL_INTERFACE:...>` Content of `...` when the property is exported using [`install(EXPORT)`](../command/install#command:install "install"), and empty otherwise.
`$<BUILD_INTERFACE:...>` Content of `...` when the property is exported using [`export()`](../command/export#command:export "export"), or when the target is used by another target in the same buildsystem. Expands to the empty string otherwise.
`$<LOWER_CASE:...>` Content of `...` converted to lower case.
`$<UPPER_CASE:...>` Content of `...` converted to upper case.
`$<MAKE_C_IDENTIFIER:...>` Content of `...` converted to a C identifier.
`$<TARGET_OBJECTS:objLib>` List of objects resulting from build of `objLib`. `objLib` must be an object of type `OBJECT_LIBRARY`.
`$<SHELL_PATH:...>` Content of `...` converted to shell path style. For example, slashes are converted to backslashes in Windows shells and drive letters are converted to posix paths in MSYS shells. The `...` must be an absolute path.
cmake cmake-modules(7) cmake-modules(7)
================
* [All Modules](#all-modules)
All Modules
-----------
* [AddFileDependencies](../module/addfiledependencies)
* [AndroidTestUtilities](../module/androidtestutilities)
* [BundleUtilities](../module/bundleutilities)
* [CheckCCompilerFlag](../module/checkccompilerflag)
* [CheckCSourceCompiles](../module/checkcsourcecompiles)
* [CheckCSourceRuns](../module/checkcsourceruns)
* [CheckCXXCompilerFlag](../module/checkcxxcompilerflag)
* [CheckCXXSourceCompiles](../module/checkcxxsourcecompiles)
* [CheckCXXSourceRuns](../module/checkcxxsourceruns)
* [CheckCXXSymbolExists](../module/checkcxxsymbolexists)
* [CheckFortranCompilerFlag](../module/checkfortrancompilerflag)
* [CheckFortranFunctionExists](../module/checkfortranfunctionexists)
* [CheckFortranSourceCompiles](../module/checkfortransourcecompiles)
* [CheckFunctionExists](../module/checkfunctionexists)
* [CheckIPOSupported](../module/checkiposupported)
* [CheckIncludeFileCXX](../module/checkincludefilecxx)
* [CheckIncludeFile](../module/checkincludefile)
* [CheckIncludeFiles](../module/checkincludefiles)
* [CheckLanguage](../module/checklanguage)
* [CheckLibraryExists](../module/checklibraryexists)
* [CheckPrototypeDefinition](../module/checkprototypedefinition)
* [CheckStructHasMember](../module/checkstructhasmember)
* [CheckSymbolExists](../module/checksymbolexists)
* [CheckTypeSize](../module/checktypesize)
* [CheckVariableExists](../module/checkvariableexists)
* [CMakeAddFortranSubdirectory](../module/cmakeaddfortransubdirectory)
* [CMakeBackwardCompatibilityCXX](../module/cmakebackwardcompatibilitycxx)
* [CMakeDependentOption](../module/cmakedependentoption)
* [CMakeDetermineVSServicePack](../module/cmakedeterminevsservicepack)
* [CMakeExpandImportedTargets](../module/cmakeexpandimportedtargets)
* [CMakeFindDependencyMacro](../module/cmakefinddependencymacro)
* [CMakeFindFrameworks](../module/cmakefindframeworks)
* [CMakeFindPackageMode](../module/cmakefindpackagemode)
* [CMakeForceCompiler](../module/cmakeforcecompiler)
* [CMakeGraphVizOptions](../module/cmakegraphvizoptions)
* [CMakePackageConfigHelpers](../module/cmakepackageconfighelpers)
* [CMakeParseArguments](../module/cmakeparsearguments)
* [CMakePrintHelpers](../module/cmakeprinthelpers)
* [CMakePrintSystemInformation](../module/cmakeprintsysteminformation)
* [CMakePushCheckState](../module/cmakepushcheckstate)
* [CMakeVerifyManifest](../module/cmakeverifymanifest)
* [CPackArchive](../module/cpackarchive)
* [CPackBundle](../module/cpackbundle)
* [CPackComponent](../module/cpackcomponent)
* [CPackCygwin](../module/cpackcygwin)
* [CPackDeb](../module/cpackdeb)
* [CPackDMG](../module/cpackdmg)
* [CPackIFW](../module/cpackifw)
* [CPackIFWConfigureFile](../module/cpackifwconfigurefile)
* [CPackNSIS](../module/cpacknsis)
* [CPackPackageMaker](../module/cpackpackagemaker)
* [CPackProductBuild](../module/cpackproductbuild)
* [CPackRPM](../module/cpackrpm)
* [CPack](../module/cpack)
* [CPackWIX](../module/cpackwix)
* [CSharpUtilities](../module/csharputilities)
* [CTest](../module/ctest)
* [CTestCoverageCollectGCOV](../module/ctestcoveragecollectgcov)
* [CTestScriptMode](../module/ctestscriptmode)
* [CTestUseLaunchers](../module/ctestuselaunchers)
* [Dart](../module/dart)
* [DeployQt4](../module/deployqt4)
* [Documentation](../module/documentation)
* [ExternalData](../module/externaldata)
* [ExternalProject](../module/externalproject)
* [FeatureSummary](../module/featuresummary)
* [FindALSA](../module/findalsa)
* [FindArmadillo](../module/findarmadillo)
* [FindASPELL](../module/findaspell)
* [FindAVIFile](../module/findavifile)
* [FindBISON](../module/findbison)
* [FindBLAS](../module/findblas)
* [FindBacktrace](../module/findbacktrace)
* [FindBoost](../module/findboost)
* [FindBullet](../module/findbullet)
* [FindBZip2](../module/findbzip2)
* [FindCABLE](../module/findcable)
* [FindCoin3D](../module/findcoin3d)
* [FindCUDA](../module/findcuda)
* [FindCups](../module/findcups)
* [FindCURL](../module/findcurl)
* [FindCurses](../module/findcurses)
* [FindCVS](../module/findcvs)
* [FindCxxTest](../module/findcxxtest)
* [FindCygwin](../module/findcygwin)
* [FindDart](../module/finddart)
* [FindDCMTK](../module/finddcmtk)
* [FindDevIL](../module/finddevil)
* [FindDoxygen](../module/finddoxygen)
* [FindEXPAT](../module/findexpat)
* [FindFLEX](../module/findflex)
* [FindFLTK2](../module/findfltk2)
* [FindFLTK](../module/findfltk)
* [FindFreetype](../module/findfreetype)
* [FindGCCXML](../module/findgccxml)
* [FindGDAL](../module/findgdal)
* [FindGettext](../module/findgettext)
* [FindGIF](../module/findgif)
* [FindGit](../module/findgit)
* [FindGLEW](../module/findglew)
* [FindGLUT](../module/findglut)
* [FindGnuplot](../module/findgnuplot)
* [FindGnuTLS](../module/findgnutls)
* [FindGSL](../module/findgsl)
* [FindGTest](../module/findgtest)
* [FindGTK2](../module/findgtk2)
* [FindGTK](../module/findgtk)
* [FindHDF5](../module/findhdf5)
* [FindHg](../module/findhg)
* [FindHSPELL](../module/findhspell)
* [FindHTMLHelp](../module/findhtmlhelp)
* [FindIce](../module/findice)
* [FindIcotool](../module/findicotool)
* [FindICU](../module/findicu)
* [FindImageMagick](../module/findimagemagick)
* [FindIntl](../module/findintl)
* [FindITK](../module/finditk)
* [FindJasper](../module/findjasper)
* [FindJava](../module/findjava)
* [FindJNI](../module/findjni)
* [FindJPEG](../module/findjpeg)
* [FindKDE3](../module/findkde3)
* [FindKDE4](../module/findkde4)
* [FindLAPACK](../module/findlapack)
* [FindLATEX](../module/findlatex)
* [FindLibArchive](../module/findlibarchive)
* [FindLibLZMA](../module/findliblzma)
* [FindLibXml2](../module/findlibxml2)
* [FindLibXslt](../module/findlibxslt)
* [FindLTTngUST](../module/findlttngust)
* [FindLua50](../module/findlua50)
* [FindLua51](../module/findlua51)
* [FindLua](../module/findlua)
* [FindMatlab](../module/findmatlab)
* [FindMFC](../module/findmfc)
* [FindMotif](../module/findmotif)
* [FindMPEG2](../module/findmpeg2)
* [FindMPEG](../module/findmpeg)
* [FindMPI](../module/findmpi)
* [FindOpenAL](../module/findopenal)
* [FindOpenCL](../module/findopencl)
* [FindOpenGL](../module/findopengl)
* [FindOpenMP](../module/findopenmp)
* [FindOpenSceneGraph](../module/findopenscenegraph)
* [FindOpenSSL](../module/findopenssl)
* [FindOpenThreads](../module/findopenthreads)
* [FindosgAnimation](../module/findosganimation)
* [FindosgDB](../module/findosgdb)
* [Findosg\_functions](../module/findosg_functions)
* [FindosgFX](../module/findosgfx)
* [FindosgGA](../module/findosgga)
* [FindosgIntrospection](../module/findosgintrospection)
* [FindosgManipulator](../module/findosgmanipulator)
* [FindosgParticle](../module/findosgparticle)
* [FindosgPresentation](../module/findosgpresentation)
* [FindosgProducer](../module/findosgproducer)
* [FindosgQt](../module/findosgqt)
* [Findosg](../module/findosg)
* [FindosgShadow](../module/findosgshadow)
* [FindosgSim](../module/findosgsim)
* [FindosgTerrain](../module/findosgterrain)
* [FindosgText](../module/findosgtext)
* [FindosgUtil](../module/findosgutil)
* [FindosgViewer](../module/findosgviewer)
* [FindosgVolume](../module/findosgvolume)
* [FindosgWidget](../module/findosgwidget)
* [FindPackageHandleStandardArgs](../module/findpackagehandlestandardargs)
* [FindPackageMessage](../module/findpackagemessage)
* [FindPerlLibs](../module/findperllibs)
* [FindPerl](../module/findperl)
* [FindPHP4](../module/findphp4)
* [FindPhysFS](../module/findphysfs)
* [FindPike](../module/findpike)
* [FindPkgConfig](../module/findpkgconfig)
* [FindPNG](../module/findpng)
* [FindPostgreSQL](../module/findpostgresql)
* [FindProducer](../module/findproducer)
* [FindProtobuf](../module/findprotobuf)
* [FindPythonInterp](../module/findpythoninterp)
* [FindPythonLibs](../module/findpythonlibs)
* [FindQt3](../module/findqt3)
* [FindQt4](../module/findqt4)
* [FindQt](../module/findqt)
* [FindQuickTime](../module/findquicktime)
* [FindRTI](../module/findrti)
* [FindRuby](../module/findruby)
* [FindSDL\_image](../module/findsdl_image)
* [FindSDL\_mixer](../module/findsdl_mixer)
* [FindSDL\_net](../module/findsdl_net)
* [FindSDL](../module/findsdl)
* [FindSDL\_sound](../module/findsdl_sound)
* [FindSDL\_ttf](../module/findsdl_ttf)
* [FindSelfPackers](../module/findselfpackers)
* [FindSquish](../module/findsquish)
* [FindSubversion](../module/findsubversion)
* [FindSWIG](../module/findswig)
* [FindTCL](../module/findtcl)
* [FindTclsh](../module/findtclsh)
* [FindTclStub](../module/findtclstub)
* [FindThreads](../module/findthreads)
* [FindTIFF](../module/findtiff)
* [FindUnixCommands](../module/findunixcommands)
* [FindVTK](../module/findvtk)
* [FindVulkan](../module/findvulkan)
* [FindWget](../module/findwget)
* [FindWish](../module/findwish)
* [FindwxWidgets](../module/findwxwidgets)
* [FindwxWindows](../module/findwxwindows)
* [FindXCTest](../module/findxctest)
* [FindXalanC](../module/findxalanc)
* [FindXercesC](../module/findxercesc)
* [FindX11](../module/findx11)
* [FindXMLRPC](../module/findxmlrpc)
* [FindZLIB](../module/findzlib)
* [FortranCInterface](../module/fortrancinterface)
* [GenerateExportHeader](../module/generateexportheader)
* [GetPrerequisites](../module/getprerequisites)
* [GNUInstallDirs](../module/gnuinstalldirs)
* [GoogleTest](../module/googletest)
* [InstallRequiredSystemLibraries](../module/installrequiredsystemlibraries)
* [MacroAddFileDependencies](../module/macroaddfiledependencies)
* [ProcessorCount](../module/processorcount)
* [SelectLibraryConfigurations](../module/selectlibraryconfigurations)
* [SquishTestScript](../module/squishtestscript)
* [TestBigEndian](../module/testbigendian)
* [TestCXXAcceptsFlag](../module/testcxxacceptsflag)
* [TestForANSIForScope](../module/testforansiforscope)
* [TestForANSIStreamHeaders](../module/testforansistreamheaders)
* [TestForSSTREAM](../module/testforsstream)
* [TestForSTDNamespace](../module/testforstdnamespace)
* [UseEcos](../module/useecos)
* [UseJavaClassFilelist](../module/usejavaclassfilelist)
* [UseJava](../module/usejava)
* [UseJavaSymlinks](../module/usejavasymlinks)
* [UsePkgConfig](../module/usepkgconfig)
* [UseSWIG](../module/useswig)
* [UsewxWidgets](../module/usewxwidgets)
* [Use\_wxWindows](../module/use_wxwindows)
* [WriteBasicConfigVersionFile](../module/writebasicconfigversionfile)
* [WriteCompilerDetectionHeader](../module/writecompilerdetectionheader)
| programming_docs |
cmake ctest(1) ctest(1)
========
Synopsis
--------
```
ctest [<options>]
```
Description
-----------
The “ctest” executable is the CMake test driver program. CMake-generated build trees created for projects that use the ENABLE\_TESTING and ADD\_TEST commands have testing support. This program will run the tests and report results.
Options
-------
`-C <cfg>, --build-config <cfg>`
Choose configuration to test.
Some CMake-generated build trees can have multiple build configurations in the same tree. This option can be used to specify which one should be tested. Example configurations are “Debug” and “Release”.
`-V,--verbose`
Enable verbose output from tests.
Test output is normally suppressed and only summary information is displayed. This option will show all test output.
`-VV,--extra-verbose`
Enable more verbose output from tests.
Test output is normally suppressed and only summary information is displayed. This option will show even more test output.
`--debug`
Displaying more verbose internals of CTest.
This feature will result in a large number of output that is mostly useful for debugging dashboard problems.
`--output-on-failure` Output anything outputted by the test program if the test should fail. This option can also be enabled by setting the environment variable `CTEST_OUTPUT_ON_FAILURE`.
`-F`
Enable failover.
This option allows ctest to resume a test set execution that was previously interrupted. If no interruption occurred, the `-F` option will have no effect.
`-j <jobs>, --parallel <jobs>`
Run the tests in parallel using the given number of jobs.
This option tells ctest to run the tests in parallel using given number of jobs. This option can also be set by setting the environment variable `CTEST_PARALLEL_LEVEL`.
`--test-load <level>`
While running tests in parallel (e.g. with `-j`), try not to start tests when they may cause the CPU load to pass above a given threshold.
When `ctest` is run as a [Dashboard Client](#dashboard-client) this sets the `TestLoad` option of the [CTest Test Step](#ctest-test-step).
`-Q,--quiet`
Make ctest quiet.
This option will suppress all the output. The output log file will still be generated if the `--output-log` is specified. Options such as `--verbose`, `--extra-verbose`, and `--debug` are ignored if `--quiet` is specified.
`-O <file>, --output-log <file>`
Output to log file.
This option tells ctest to write all its output to a log file.
`-N,--show-only`
Disable actual execution of tests.
This option tells ctest to list the tests that would be run but not actually run them. Useful in conjunction with the `-R` and `-E` options.
`-L <regex>, --label-regex <regex>`
Run tests with labels matching regular expression.
This option tells ctest to run only the tests whose labels match the given regular expression.
`-R <regex>, --tests-regex <regex>`
Run tests matching regular expression.
This option tells ctest to run only the tests whose names match the given regular expression.
`-E <regex>, --exclude-regex <regex>`
Exclude tests matching regular expression.
This option tells ctest to NOT run the tests whose names match the given regular expression.
`-LE <regex>, --label-exclude <regex>`
Exclude tests with labels matching regular expression.
This option tells ctest to NOT run the tests whose labels match the given regular expression.
`-FA <regex>, --fixture-exclude-any <regex>`
Exclude fixtures matching `<regex>` from automatically adding any tests to the test set.
If a test in the set of tests to be executed requires a particular fixture, that fixture’s setup and cleanup tests would normally be added to the test set automatically. This option prevents adding setup or cleanup tests for fixtures matching the `<regex>`. Note that all other fixture behavior is retained, including test dependencies and skipping tests that have fixture setup tests that fail.
`-FS <regex>, --fixture-exclude-setup <regex>` Same as `-FA` except only matching setup tests are excluded.
`-FC <regex>, --fixture-exclude-cleanup <regex>` Same as `-FA` except only matching cleanup tests are excluded.
`-D <dashboard>, --dashboard <dashboard>`
Execute dashboard test.
This option tells ctest to act as a CDash client and perform a dashboard test. All tests are <Mode><Test>, where Mode can be Experimental, Nightly, and Continuous, and Test can be Start, Update, Configure, Build, Test, Coverage, and Submit.
`-D <var>:<type>=<value>`
Define a variable for script mode.
Pass in variable values on the command line. Use in conjunction with `-S` to pass variable values to a dashboard script. Parsing `-D` arguments as variable values is only attempted if the value following `-D` does not match any of the known dashboard types.
`-M <model>, --test-model <model>`
Sets the model for a dashboard.
This option tells ctest to act as a CDash client where the `<model>` can be `Experimental`, `Nightly`, and `Continuous`. Combining `-M` and `-T` is similar to `-D`.
`-T <action>, --test-action <action>`
Sets the dashboard action to perform.
This option tells ctest to act as a CDash client and perform some action such as `start`, `build`, `test` etc. See [Dashboard Client Steps](#dashboard-client-steps) for the full list of actions. Combining `-M` and `-T` is similar to `-D`.
`--track <track>`
Specify the track to submit dashboard to
Submit dashboard to specified track instead of default one. By default, the dashboard is submitted to Nightly, Experimental, or Continuous track, but by specifying this option, the track can be arbitrary.
`-S <script>, --script <script>`
Execute a dashboard for a configuration.
This option tells ctest to load in a configuration script which sets a number of parameters such as the binary and source directories. Then ctest will do what is required to create and run a dashboard. This option basically sets up a dashboard and then runs `ctest -D` with the appropriate options.
`-SP <script>, --script-new-process <script>`
Execute a dashboard for a configuration.
This option does the same operations as `-S` but it will do them in a separate process. This is primarily useful in cases where the script may modify the environment and you do not want the modified environment to impact other `-S` scripts.
`-A <file>, --add-notes <file>`
Add a notes file with submission.
This option tells ctest to include a notes file when submitting dashboard.
`-I [Start,End,Stride,test#,test#|Test file], --tests-information`
Run a specific number of tests by number.
This option causes ctest to run tests starting at number Start, ending at number End, and incrementing by Stride. Any additional numbers after Stride are considered individual test numbers. Start, End,or stride can be empty. Optionally a file can be given that contains the same syntax as the command line.
`-U, --union`
Take the Union of `-I` and `-R`.
When both `-R` and `-I` are specified by default the intersection of tests are run. By specifying `-U` the union of tests is run instead.
`--rerun-failed`
Run only the tests that failed previously.
This option tells ctest to perform only the tests that failed during its previous run. When this option is specified, ctest ignores all other options intended to modify the list of tests to run (`-L`, `-R`, `-E`, `-LE`, `-I`, etc). In the event that CTest runs and no tests fail, subsequent calls to ctest with the `--rerun-failed` option will run the set of tests that most recently failed (if any).
`--repeat-until-fail <n>`
Require each test to run `<n>` times without failing in order to pass.
This is useful in finding sporadic failures in test cases.
`--max-width <width>`
Set the max width for a test name to output.
Set the maximum width for each test name to show in the output. This allows the user to widen the output to avoid clipping the test name which can be very annoying.
`--interactive-debug-mode [0|1]`
Set the interactive mode to 0 or 1.
This option causes ctest to run tests in either an interactive mode or a non-interactive mode. On Windows this means that in non-interactive mode, all system debug pop up windows are blocked. In dashboard mode (Experimental, Nightly, Continuous), the default is non-interactive. When just running tests not for a dashboard the default is to allow popups and interactive debugging.
`--no-label-summary`
Disable timing summary information for labels.
This option tells ctest not to print summary information for each label associated with the tests run. If there are no labels on the tests, nothing extra is printed.
`--build-and-test <path-to-source> <path-to-build>`
Configure, build and run a test.
This option tells ctest to configure (i.e. run cmake on), build, and or execute a test. The configure and test steps are optional. The arguments to this command line are the source and binary directories. The `--build-generator` option *must* be provided to use `--build-and-test`. If `--test-command` is specified then that will be run after the build is complete. Other options that affect this mode are `--build-target`, `--build-nocmake`, `--build-run-dir`, `--build-two-config`, `--build-exe-dir`, `--build-project`, `--build-noclean` and `--build-options`.
`--build-target`
Specify a specific target to build.
This option goes with the `--build-and-test` option, if left out the `all` target is built.
`--build-nocmake`
Run the build without running cmake first.
Skip the cmake step.
`--build-run-dir`
Specify directory to run programs from.
Directory where programs will be after it has been compiled.
`--build-two-config` Run CMake twice.
`--build-exe-dir` Specify the directory for the executable.
`--build-generator` Specify the generator to use. See the [`cmake-generators(7)`](cmake-generators.7#manual:cmake-generators(7) "cmake-generators(7)") manual.
`--build-generator-platform` Specify the generator-specific platform.
`--build-generator-toolset` Specify the generator-specific toolset.
`--build-project` Specify the name of the project to build.
`--build-makeprogram` Override the make program chosen by CTest with a given one.
`--build-noclean` Skip the make clean step.
`--build-config-sample` A sample executable to use to determine the configuration that should be used. e.g. Debug/Release/etc.
`--build-options`
Add extra options to the build step.
This option must be the last option with the exception of `--test-command`
`--test-command` The test to run with the `--build-and-test` option.
`--test-output-size-passed <size>` Limit the output for passed tests to `<size>` bytes.
`--test-output-size-failed <size>` Limit the output for failed tests to `<size>` bytes.
`--test-timeout` The time limit in seconds, internal use only.
`--tomorrow-tag`
Nightly or experimental starts with next day tag.
This is useful if the build will not finish in one day.
`--ctest-config`
The configuration file used to initialize CTest state when submitting dashboards.
This option tells CTest to use different initialization file instead of CTestConfiguration.tcl. This way multiple initialization files can be used for example to submit to multiple dashboards.
`--overwrite`
Overwrite CTest configuration option.
By default ctest uses configuration options from configuration file. This option will overwrite the configuration option.
`--extra-submit <file>[;<file>]`
Submit extra files to the dashboard.
This option will submit extra files to the dashboard.
`--force-new-ctest-process`
Run child CTest instances as new processes.
By default CTest will run child CTest instances within the same process. If this behavior is not desired, this argument will enforce new processes for child CTest processes.
`--schedule-random`
Use a random order for scheduling tests.
This option will run the tests in a random order. It is commonly used to detect implicit dependencies in a test suite.
`--submit-index` Legacy option for old Dart2 dashboard server feature. Do not use.
`--timeout <seconds>`
Set a global timeout on all tests.
This option will set a global timeout on all tests that do not already have a timeout set on them.
`--stop-time <time>`
Set a time at which all tests should stop running.
Set a real time of day at which all tests should timeout. Example: `7:00:00 -0400`. Any time format understood by the curl date parser is accepted. Local time is assumed if no timezone is specified.
`--http1.0`
Submit using HTTP 1.0.
This option will force CTest to use HTTP 1.0 to submit files to the dashboard, instead of HTTP 1.1.
`--no-compress-output`
Do not compress test output when submitting.
This flag will turn off automatic compression of test output. Use this to maintain compatibility with an older version of CDash which doesn’t support compressed test output.
`--print-labels`
Print all available test labels.
This option will not run any tests, it will simply print the list of all labels associated with the test set.
`--help,-help,-usage,-h,-H,/?`
Print usage information and exit.
Usage describes the basic command line interface and its options.
`--version,-version,/V [<f>]`
Show program name/version banner and exit.
If a file is specified, the version is written into it. The help is printed to a named <f>ile if given.
`--help-full [<f>]`
Print all help manuals and exit.
All manuals are printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-manual <man> [<f>]`
Print one help manual and exit.
The specified manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-manual-list [<f>]`
List help manuals available and exit.
The list contains all manuals for which help may be obtained by using the `--help-manual` option followed by a manual name. The help is printed to a named <f>ile if given.
`--help-command <cmd> [<f>]`
Print help for one command and exit.
The [`cmake-commands(7)`](cmake-commands.7#manual:cmake-commands(7) "cmake-commands(7)") manual entry for `<cmd>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-command-list [<f>]`
List commands with help available and exit.
The list contains all commands for which help may be obtained by using the `--help-command` option followed by a command name. The help is printed to a named <f>ile if given.
`--help-commands [<f>]`
Print cmake-commands manual and exit.
The [`cmake-commands(7)`](cmake-commands.7#manual:cmake-commands(7) "cmake-commands(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-module <mod> [<f>]`
Print help for one module and exit.
The [`cmake-modules(7)`](cmake-modules.7#manual:cmake-modules(7) "cmake-modules(7)") manual entry for `<mod>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-module-list [<f>]`
List modules with help available and exit.
The list contains all modules for which help may be obtained by using the `--help-module` option followed by a module name. The help is printed to a named <f>ile if given.
`--help-modules [<f>]`
Print cmake-modules manual and exit.
The [`cmake-modules(7)`](cmake-modules.7#manual:cmake-modules(7) "cmake-modules(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-policy <cmp> [<f>]`
Print help for one policy and exit.
The [`cmake-policies(7)`](cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") manual entry for `<cmp>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-policy-list [<f>]`
List policies with help available and exit.
The list contains all policies for which help may be obtained by using the `--help-policy` option followed by a policy name. The help is printed to a named <f>ile if given.
`--help-policies [<f>]`
Print cmake-policies manual and exit.
The [`cmake-policies(7)`](cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-property <prop> [<f>]`
Print help for one property and exit.
The [`cmake-properties(7)`](cmake-properties.7#manual:cmake-properties(7) "cmake-properties(7)") manual entries for `<prop>` are printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-property-list [<f>]`
List properties with help available and exit.
The list contains all properties for which help may be obtained by using the `--help-property` option followed by a property name. The help is printed to a named <f>ile if given.
`--help-properties [<f>]`
Print cmake-properties manual and exit.
The [`cmake-properties(7)`](cmake-properties.7#manual:cmake-properties(7) "cmake-properties(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-variable <var> [<f>]`
Print help for one variable and exit.
The [`cmake-variables(7)`](cmake-variables.7#manual:cmake-variables(7) "cmake-variables(7)") manual entry for `<var>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-variable-list [<f>]`
List variables with help available and exit.
The list contains all variables for which help may be obtained by using the `--help-variable` option followed by a variable name. The help is printed to a named <f>ile if given.
`--help-variables [<f>]`
Print cmake-variables manual and exit.
The [`cmake-variables(7)`](cmake-variables.7#manual:cmake-variables(7) "cmake-variables(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
Dashboard Client
----------------
CTest can operate as a client for the [CDash](http://cdash.org/) software quality dashboard application. As a dashboard client, CTest performs a sequence of steps to configure, build, and test software, and then submits the results to a [CDash](http://cdash.org/) server.
### Dashboard Client Steps
CTest defines an ordered list of testing steps of which some or all may be run as a dashboard client:
`Start` Start a new dashboard submission to be composed of results recorded by the following steps. See the [CTest Start Step](#ctest-start-step) section below.
`Update` Update the source tree from its version control repository. Record the old and new versions and the list of updated source files. See the [CTest Update Step](#ctest-update-step) section below.
`Configure` Configure the software by running a command in the build tree. Record the configuration output log. See the [CTest Configure Step](#ctest-configure-step) section below.
`Build` Build the software by running a command in the build tree. Record the build output log and detect warnings and errors. See the [CTest Build Step](#ctest-build-step) section below.
`Test` Test the software by loading a `CTestTestfile.cmake` from the build tree and executing the defined tests. Record the output and result of each test. See the [CTest Test Step](#ctest-test-step) section below.
`Coverage` Compute coverage of the source code by running a coverage analysis tool and recording its output. See the [CTest Coverage Step](#ctest-coverage-step) section below.
`MemCheck` Run the software test suite through a memory check tool. Record the test output, results, and issues reported by the tool. See the [CTest MemCheck Step](#ctest-memcheck-step) section below.
`Submit` Submit results recorded from other testing steps to the software quality dashboard server. See the [CTest Submit Step](#ctest-submit-step) section below. ### Dashboard Client Modes
CTest defines three modes of operation as a dashboard client:
`Nightly` This mode is intended to be invoked once per day, typically at night. It enables the `Start`, `Update`, `Configure`, `Build`, `Test`, `Coverage`, and `Submit` steps by default. Selected steps run even if the `Update` step reports no changes to the source tree.
`Continuous` This mode is intended to be invoked repeatedly throughout the day. It enables the `Start`, `Update`, `Configure`, `Build`, `Test`, `Coverage`, and `Submit` steps by default, but exits after the `Update` step if it reports no changes to the source tree.
`Experimental` This mode is intended to be invoked by a developer to test local changes. It enables the `Start`, `Configure`, `Build`, `Test`, `Coverage`, and `Submit` steps by default. ### Dashboard Client via CTest Command-Line
CTest can perform testing on an already-generated build tree. Run the `ctest` command with the current working directory set to the build tree and use one of these signatures:
```
ctest -D <mode>[<step>]
ctest -M <mode> [ -T <step> ]...
```
The `<mode>` must be one of the above [Dashboard Client Modes](#dashboard-client-modes), and each `<step>` must be one of the above [Dashboard Client Steps](#dashboard-client-steps).
CTest reads the [Dashboard Client Configuration](#dashboard-client-configuration) settings from a file in the build tree called either `CTestConfiguration.ini` or `DartConfiguration.tcl` (the names are historical). The format of the file is:
```
# Lines starting in '#' are comments.
# Other non-blank lines are key-value pairs.
<setting>: <value>
```
where `<setting>` is the setting name and `<value>` is the setting value.
In build trees generated by CMake, this configuration file is generated by the [`CTest`](../module/ctest#module:CTest "CTest") module if included by the project. The module uses variables to obtain a value for each setting as documented with the settings below.
### Dashboard Client via CTest Script
CTest can perform testing driven by a [`cmake-language(7)`](cmake-language.7#manual:cmake-language(7) "cmake-language(7)") script that creates and maintains the source and build tree as well as performing the testing steps. Run the `ctest` command with the current working directory set outside of any build tree and use one of these signatures:
```
ctest -S <script>
ctest -SP <script>
```
The `<script>` file must call [CTest Commands](cmake-commands.7#ctest-commands) commands to run testing steps explicitly as documented below. The commands obtain [Dashboard Client Configuration](#dashboard-client-configuration) settings from their arguments or from variables set in the script.
Dashboard Client Configuration
------------------------------
The [Dashboard Client Steps](#dashboard-client-steps) may be configured by named settings as documented in the following sections.
### CTest Start Step
Start a new dashboard submission to be composed of results recorded by the following steps.
In a [CTest Script](#ctest-script), the [`ctest_start()`](../command/ctest_start#command:ctest_start "ctest_start") command runs this step. Arguments to the command may specify some of the step settings. The command first runs the command-line specified by the `CTEST_CHECKOUT_COMMAND` variable, if set, to initialize the source directory.
Configuration settings include:
`BuildDirectory`
The full path to the project build tree.
* [CTest Script](#ctest-script) variable: [`CTEST_BINARY_DIRECTORY`](../variable/ctest_binary_directory#variable:CTEST_BINARY_DIRECTORY "CTEST_BINARY_DIRECTORY")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: [`PROJECT_BINARY_DIR`](../variable/project_binary_dir#variable:PROJECT_BINARY_DIR "PROJECT_BINARY_DIR")
`SourceDirectory`
The full path to the project source tree.
* [CTest Script](#ctest-script) variable: [`CTEST_SOURCE_DIRECTORY`](../variable/ctest_source_directory#variable:CTEST_SOURCE_DIRECTORY "CTEST_SOURCE_DIRECTORY")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: [`PROJECT_SOURCE_DIR`](../variable/project_source_dir#variable:PROJECT_SOURCE_DIR "PROJECT_SOURCE_DIR")
### CTest Update Step
In a [CTest Script](#ctest-script), the [`ctest_update()`](../command/ctest_update#command:ctest_update "ctest_update") command runs this step. Arguments to the command may specify some of the step settings.
Configuration settings to specify the version control tool include:
`BZRCommand`
`bzr` command-line tool to use if source tree is managed by Bazaar.
* [CTest Script](#ctest-script) variable: [`CTEST_BZR_COMMAND`](../variable/ctest_bzr_command#variable:CTEST_BZR_COMMAND "CTEST_BZR_COMMAND")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: none
`BZRUpdateOptions`
Command-line options to the `BZRCommand` when updating the source.
* [CTest Script](#ctest-script) variable: [`CTEST_BZR_UPDATE_OPTIONS`](../variable/ctest_bzr_update_options#variable:CTEST_BZR_UPDATE_OPTIONS "CTEST_BZR_UPDATE_OPTIONS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: none
`CVSCommand`
`cvs` command-line tool to use if source tree is managed by CVS.
* [CTest Script](#ctest-script) variable: [`CTEST_CVS_COMMAND`](../variable/ctest_cvs_command#variable:CTEST_CVS_COMMAND "CTEST_CVS_COMMAND")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CVSCOMMAND`
`CVSUpdateOptions`
Command-line options to the `CVSCommand` when updating the source.
* [CTest Script](#ctest-script) variable: [`CTEST_CVS_UPDATE_OPTIONS`](../variable/ctest_cvs_update_options#variable:CTEST_CVS_UPDATE_OPTIONS "CTEST_CVS_UPDATE_OPTIONS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CVS_UPDATE_OPTIONS`
`GITCommand`
`git` command-line tool to use if source tree is managed by Git.
* [CTest Script](#ctest-script) variable: [`CTEST_GIT_COMMAND`](../variable/ctest_git_command#variable:CTEST_GIT_COMMAND "CTEST_GIT_COMMAND")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `GITCOMMAND`
The source tree is updated by `git fetch` followed by `git reset --hard` to the `FETCH_HEAD`. The result is the same as `git pull` except that any local moficiations are overwritten. Use `GITUpdateCustom` to specify a different approach.
`GITInitSubmodules`
If set, CTest will update the repository’s submodules before updating.
* [CTest Script](#ctest-script) variable: [`CTEST_GIT_INIT_SUBMODULES`](../variable/ctest_git_init_submodules#variable:CTEST_GIT_INIT_SUBMODULES "CTEST_GIT_INIT_SUBMODULES")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_GIT_INIT_SUBMODULES`
`GITUpdateCustom`
Specify a custom command line (as a semicolon-separated list) to run in the source tree (Git work tree) to update it instead of running the `GITCommand`.
* [CTest Script](#ctest-script) variable: [`CTEST_GIT_UPDATE_CUSTOM`](../variable/ctest_git_update_custom#variable:CTEST_GIT_UPDATE_CUSTOM "CTEST_GIT_UPDATE_CUSTOM")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_GIT_UPDATE_CUSTOM`
`GITUpdateOptions`
Command-line options to the `GITCommand` when updating the source.
* [CTest Script](#ctest-script) variable: [`CTEST_GIT_UPDATE_OPTIONS`](../variable/ctest_git_update_options#variable:CTEST_GIT_UPDATE_OPTIONS "CTEST_GIT_UPDATE_OPTIONS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `GIT_UPDATE_OPTIONS`
`HGCommand`
`hg` command-line tool to use if source tree is managed by Mercurial.
* [CTest Script](#ctest-script) variable: [`CTEST_HG_COMMAND`](../variable/ctest_hg_command#variable:CTEST_HG_COMMAND "CTEST_HG_COMMAND")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: none
`HGUpdateOptions`
Command-line options to the `HGCommand` when updating the source.
* [CTest Script](#ctest-script) variable: [`CTEST_HG_UPDATE_OPTIONS`](../variable/ctest_hg_update_options#variable:CTEST_HG_UPDATE_OPTIONS "CTEST_HG_UPDATE_OPTIONS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: none
`P4Client`
Value of the `-c` option to the `P4Command`.
* [CTest Script](#ctest-script) variable: [`CTEST_P4_CLIENT`](../variable/ctest_p4_client#variable:CTEST_P4_CLIENT "CTEST_P4_CLIENT")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_P4_CLIENT`
`P4Command`
`p4` command-line tool to use if source tree is managed by Perforce.
* [CTest Script](#ctest-script) variable: [`CTEST_P4_COMMAND`](../variable/ctest_p4_command#variable:CTEST_P4_COMMAND "CTEST_P4_COMMAND")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `P4COMMAND`
`P4Options`
Command-line options to the `P4Command` for all invocations.
* [CTest Script](#ctest-script) variable: [`CTEST_P4_OPTIONS`](../variable/ctest_p4_options#variable:CTEST_P4_OPTIONS "CTEST_P4_OPTIONS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_P4_OPTIONS`
`P4UpdateCustom`
Specify a custom command line (as a semicolon-separated list) to run in the source tree (Perforce tree) to update it instead of running the `P4Command`.
* [CTest Script](#ctest-script) variable: none
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_P4_UPDATE_CUSTOM`
`P4UpdateOptions`
Command-line options to the `P4Command` when updating the source.
* [CTest Script](#ctest-script) variable: [`CTEST_P4_UPDATE_OPTIONS`](../variable/ctest_p4_update_options#variable:CTEST_P4_UPDATE_OPTIONS "CTEST_P4_UPDATE_OPTIONS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_P4_UPDATE_OPTIONS`
`SVNCommand`
`svn` command-line tool to use if source tree is managed by Subversion.
* [CTest Script](#ctest-script) variable: [`CTEST_SVN_COMMAND`](../variable/ctest_svn_command#variable:CTEST_SVN_COMMAND "CTEST_SVN_COMMAND")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `SVNCOMMAND`
`SVNOptions`
Command-line options to the `SVNCommand` for all invocations.
* [CTest Script](#ctest-script) variable: [`CTEST_SVN_OPTIONS`](../variable/ctest_svn_options#variable:CTEST_SVN_OPTIONS "CTEST_SVN_OPTIONS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_SVN_OPTIONS`
`SVNUpdateOptions`
Command-line options to the `SVNCommand` when updating the source.
* [CTest Script](#ctest-script) variable: [`CTEST_SVN_UPDATE_OPTIONS`](../variable/ctest_svn_update_options#variable:CTEST_SVN_UPDATE_OPTIONS "CTEST_SVN_UPDATE_OPTIONS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `SVN_UPDATE_OPTIONS`
`UpdateCommand`
Specify the version-control command-line tool to use without detecting the VCS that manages the source tree.
* [CTest Script](#ctest-script) variable: [`CTEST_UPDATE_COMMAND`](../variable/ctest_update_command#variable:CTEST_UPDATE_COMMAND "CTEST_UPDATE_COMMAND")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `<VCS>COMMAND` when `UPDATE_TYPE` is `<vcs>`, else `UPDATE_COMMAND`
`UpdateOptions`
Command-line options to the `UpdateCommand`.
* [CTest Script](#ctest-script) variable: [`CTEST_UPDATE_OPTIONS`](../variable/ctest_update_options#variable:CTEST_UPDATE_OPTIONS "CTEST_UPDATE_OPTIONS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `<VCS>_UPDATE_OPTIONS` when `UPDATE_TYPE` is `<vcs>`, else `UPDATE_OPTIONS`
`UpdateType`
Specify the version-control system that manages the source tree if it cannot be detected automatically. The value may be `bzr`, `cvs`, `git`, `hg`, `p4`, or `svn`.
* [CTest Script](#ctest-script) variable: none, detected from source tree
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `UPDATE_TYPE` if set, else `CTEST_UPDATE_TYPE`
`UpdateVersionOnly`
Specify that you want the version control update command to only discover the current version that is checked out, and not to update to a different version.
* [CTest Script](#ctest-script) variable: [`CTEST_UPDATE_VERSION_ONLY`](../variable/ctest_update_version_only#variable:CTEST_UPDATE_VERSION_ONLY "CTEST_UPDATE_VERSION_ONLY")
Additional configuration settings include:
`NightlyStartTime`
In the `Nightly` dashboard mode, specify the “nightly start time”. With centralized version control systems (`cvs` and `svn`), the `Update` step checks out the version of the software as of this time so that multiple clients choose a common version to test. This is not well-defined in distributed version-control systems so the setting is ignored.
* [CTest Script](#ctest-script) variable: [`CTEST_NIGHTLY_START_TIME`](../variable/ctest_nightly_start_time#variable:CTEST_NIGHTLY_START_TIME "CTEST_NIGHTLY_START_TIME")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `NIGHTLY_START_TIME` if set, else `CTEST_NIGHTLY_START_TIME`
### CTest Configure Step
In a [CTest Script](#ctest-script), the [`ctest_configure()`](../command/ctest_configure#command:ctest_configure "ctest_configure") command runs this step. Arguments to the command may specify some of the step settings.
Configuration settings include:
`ConfigureCommand`
Command-line to launch the software configuration process. It will be executed in the location specified by the `BuildDirectory` setting.
* [CTest Script](#ctest-script) variable: [`CTEST_CONFIGURE_COMMAND`](../variable/ctest_configure_command#variable:CTEST_CONFIGURE_COMMAND "CTEST_CONFIGURE_COMMAND")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: [`CMAKE_COMMAND`](../variable/cmake_command#variable:CMAKE_COMMAND "CMAKE_COMMAND") followed by [`PROJECT_SOURCE_DIR`](../variable/project_source_dir#variable:PROJECT_SOURCE_DIR "PROJECT_SOURCE_DIR")
### CTest Build Step
In a [CTest Script](#ctest-script), the [`ctest_build()`](../command/ctest_build#command:ctest_build "ctest_build") command runs this step. Arguments to the command may specify some of the step settings.
Configuration settings include:
`DefaultCTestConfigurationType`
When the build system to be launched allows build-time selection of the configuration (e.g. `Debug`, `Release`), this specifies the default configuration to be built when no `-C` option is given to the `ctest` command. The value will be substituted into the value of `MakeCommand` to replace the literal string `${CTEST_CONFIGURATION_TYPE}` if it appears.
* [CTest Script](#ctest-script) variable: [`CTEST_CONFIGURATION_TYPE`](../variable/ctest_configuration_type#variable:CTEST_CONFIGURATION_TYPE "CTEST_CONFIGURATION_TYPE")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `DEFAULT_CTEST_CONFIGURATION_TYPE`, initialized by the `CMAKE_CONFIG_TYPE` environment variable
`MakeCommand`
Command-line to launch the software build process. It will be executed in the location specified by the `BuildDirectory` setting.
* [CTest Script](#ctest-script) variable: [`CTEST_BUILD_COMMAND`](../variable/ctest_build_command#variable:CTEST_BUILD_COMMAND "CTEST_BUILD_COMMAND")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `MAKECOMMAND`, initialized by the [`build_command()`](../command/build_command#command:build_command "build_command") command
`UseLaunchers`
For build trees generated by CMake using one of the [Makefile Generators](cmake-generators.7#makefile-generators) or the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator, specify whether the `CTEST_USE_LAUNCHERS` feature is enabled by the [`CTestUseLaunchers`](../module/ctestuselaunchers#module:CTestUseLaunchers "CTestUseLaunchers") module (also included by the [`CTest`](../module/ctest#module:CTest "CTest") module). When enabled, the generated build system wraps each invocation of the compiler, linker, or custom command line with a “launcher” that communicates with CTest via environment variables and files to report granular build warning and error information. Otherwise, CTest must “scrape” the build output log for diagnostics.
* [CTest Script](#ctest-script) variable: [`CTEST_USE_LAUNCHERS`](../variable/ctest_use_launchers#variable:CTEST_USE_LAUNCHERS "CTEST_USE_LAUNCHERS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_USE_LAUNCHERS`
### CTest Test Step
In a [CTest Script](#ctest-script), the [`ctest_test()`](../command/ctest_test#command:ctest_test "ctest_test") command runs this step. Arguments to the command may specify some of the step settings.
Configuration settings include:
`TestLoad`
While running tests in parallel (e.g. with `-j`), try not to start tests when they may cause the CPU load to pass above a given threshold.
* [CTest Script](#ctest-script) variable: [`CTEST_TEST_LOAD`](../variable/ctest_test_load#variable:CTEST_TEST_LOAD "CTEST_TEST_LOAD")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_TEST_LOAD`
`TimeOut`
The default timeout for each test if not specified by the [`TIMEOUT`](../prop_test/timeout#prop_test:TIMEOUT "TIMEOUT") test property.
* [CTest Script](#ctest-script) variable: [`CTEST_TEST_TIMEOUT`](../variable/ctest_test_timeout#variable:CTEST_TEST_TIMEOUT "CTEST_TEST_TIMEOUT")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `DART_TESTING_TIMEOUT`
### CTest Coverage Step
In a [CTest Script](#ctest-script), the [`ctest_coverage()`](../command/ctest_coverage#command:ctest_coverage "ctest_coverage") command runs this step. Arguments to the command may specify some of the step settings.
Configuration settings include:
`CoverageCommand`
Command-line tool to perform software coverage analysis. It will be executed in the location specified by the `BuildDirectory` setting.
* [CTest Script](#ctest-script) variable: [`CTEST_COVERAGE_COMMAND`](../variable/ctest_coverage_command#variable:CTEST_COVERAGE_COMMAND "CTEST_COVERAGE_COMMAND")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `COVERAGE_COMMAND`
`CoverageExtraFlags`
Specify command-line options to the `CoverageCommand` tool.
* [CTest Script](#ctest-script) variable: [`CTEST_COVERAGE_EXTRA_FLAGS`](../variable/ctest_coverage_extra_flags#variable:CTEST_COVERAGE_EXTRA_FLAGS "CTEST_COVERAGE_EXTRA_FLAGS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `COVERAGE_EXTRA_FLAGS`
### CTest MemCheck Step
In a [CTest Script](#ctest-script), the [`ctest_memcheck()`](../command/ctest_memcheck#command:ctest_memcheck "ctest_memcheck") command runs this step. Arguments to the command may specify some of the step settings.
Configuration settings include:
`MemoryCheckCommand`
Command-line tool to perform dynamic analysis. Test command lines will be launched through this tool.
* [CTest Script](#ctest-script) variable: [`CTEST_MEMORYCHECK_COMMAND`](../variable/ctest_memorycheck_command#variable:CTEST_MEMORYCHECK_COMMAND "CTEST_MEMORYCHECK_COMMAND")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `MEMORYCHECK_COMMAND`
`MemoryCheckCommandOptions`
Specify command-line options to the `MemoryCheckCommand` tool. They will be placed prior to the test command line.
* [CTest Script](#ctest-script) variable: [`CTEST_MEMORYCHECK_COMMAND_OPTIONS`](../variable/ctest_memorycheck_command_options#variable:CTEST_MEMORYCHECK_COMMAND_OPTIONS "CTEST_MEMORYCHECK_COMMAND_OPTIONS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `MEMORYCHECK_COMMAND_OPTIONS`
`MemoryCheckType`
Specify the type of memory checking to perform.
* [CTest Script](#ctest-script) variable: [`CTEST_MEMORYCHECK_TYPE`](../variable/ctest_memorycheck_type#variable:CTEST_MEMORYCHECK_TYPE "CTEST_MEMORYCHECK_TYPE")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `MEMORYCHECK_TYPE`
`MemoryCheckSanitizerOptions`
Specify options to sanitizers when running with a sanitize-enabled build.
* [CTest Script](#ctest-script) variable: [`CTEST_MEMORYCHECK_SANITIZER_OPTIONS`](../variable/ctest_memorycheck_sanitizer_options#variable:CTEST_MEMORYCHECK_SANITIZER_OPTIONS "CTEST_MEMORYCHECK_SANITIZER_OPTIONS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `MEMORYCHECK_SANITIZER_OPTIONS`
`MemoryCheckSuppressionFile`
Specify a file containing suppression rules for the `MemoryCheckCommand` tool. It will be passed with options appropriate to the tool.
* [CTest Script](#ctest-script) variable: [`CTEST_MEMORYCHECK_SUPPRESSIONS_FILE`](../variable/ctest_memorycheck_suppressions_file#variable:CTEST_MEMORYCHECK_SUPPRESSIONS_FILE "CTEST_MEMORYCHECK_SUPPRESSIONS_FILE")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `MEMORYCHECK_SUPPRESSIONS_FILE`
Additional configuration settings include:
`BoundsCheckerCommand`
Specify a `MemoryCheckCommand` that is known to be command-line compatible with Bounds Checker.
* [CTest Script](#ctest-script) variable: none
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: none
`PurifyCommand`
Specify a `MemoryCheckCommand` that is known to be command-line compatible with Purify.
* [CTest Script](#ctest-script) variable: none
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `PURIFYCOMMAND`
`ValgrindCommand`
Specify a `MemoryCheckCommand` that is known to be command-line compatible with Valgrind.
* [CTest Script](#ctest-script) variable: none
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `VALGRIND_COMMAND`
`ValgrindCommandOptions`
Specify command-line options to the `ValgrindCommand` tool. They will be placed prior to the test command line.
* [CTest Script](#ctest-script) variable: none
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `VALGRIND_COMMAND_OPTIONS`
### CTest Submit Step
In a [CTest Script](#ctest-script), the [`ctest_submit()`](../command/ctest_submit#command:ctest_submit "ctest_submit") command runs this step. Arguments to the command may specify some of the step settings.
Configuration settings include:
`BuildName`
Describe the dashboard client platform with a short string. (Operating system, compiler, etc.)
* [CTest Script](#ctest-script) variable: [`CTEST_BUILD_NAME`](../variable/ctest_build_name#variable:CTEST_BUILD_NAME "CTEST_BUILD_NAME")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `BUILDNAME`
`CDashVersion`
Specify the version of [CDash](http://cdash.org/) on the server.
* [CTest Script](#ctest-script) variable: none, detected from server
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_CDASH_VERSION`
`CTestSubmitRetryCount`
Specify a number of attempts to retry submission on network failure.
* [CTest Script](#ctest-script) variable: none, use the [`ctest_submit()`](../command/ctest_submit#command:ctest_submit "ctest_submit") `RETRY_COUNT` option.
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_SUBMIT_RETRY_COUNT`
`CTestSubmitRetryDelay`
Specify a delay before retrying submission on network failure.
* [CTest Script](#ctest-script) variable: none, use the [`ctest_submit()`](../command/ctest_submit#command:ctest_submit "ctest_submit") `RETRY_DELAY` option.
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_SUBMIT_RETRY_DELAY`
`CurlOptions`
Specify a semicolon-separated list of options to control the Curl library that CTest uses internally to connect to the server. Possible options are `CURLOPT_SSL_VERIFYPEER_OFF` and `CURLOPT_SSL_VERIFYHOST_OFF`.
* [CTest Script](#ctest-script) variable: [`CTEST_CURL_OPTIONS`](../variable/ctest_curl_options#variable:CTEST_CURL_OPTIONS "CTEST_CURL_OPTIONS")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_CURL_OPTIONS`
`DropLocation`
The path on the dashboard server to send the submission.
* [CTest Script](#ctest-script) variable: [`CTEST_DROP_LOCATION`](../variable/ctest_drop_location#variable:CTEST_DROP_LOCATION "CTEST_DROP_LOCATION")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `DROP_LOCATION` if set, else `CTEST_DROP_LOCATION`
`DropMethod`
Specify the method by which results should be submitted to the dashboard server. The value may be `cp`, `ftp`, `http`, `https`, `scp`, or `xmlrpc` (if CMake was built with support for it).
* [CTest Script](#ctest-script) variable: [`CTEST_DROP_METHOD`](../variable/ctest_drop_method#variable:CTEST_DROP_METHOD "CTEST_DROP_METHOD")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `DROP_METHOD` if set, else `CTEST_DROP_METHOD`
`DropSite`
The dashboard server name (for `ftp`, `http`, and `https`, `scp`, and `xmlrpc`).
* [CTest Script](#ctest-script) variable: [`CTEST_DROP_SITE`](../variable/ctest_drop_site#variable:CTEST_DROP_SITE "CTEST_DROP_SITE")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `DROP_SITE` if set, else `CTEST_DROP_SITE`
`DropSitePassword`
The dashboard server login password, if any (for `ftp`, `http`, and `https`).
* [CTest Script](#ctest-script) variable: [`CTEST_DROP_SITE_PASSWORD`](../variable/ctest_drop_site_password#variable:CTEST_DROP_SITE_PASSWORD "CTEST_DROP_SITE_PASSWORD")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `DROP_SITE_PASSWORD` if set, else `CTEST_DROP_SITE_PASWORD`
`DropSiteUser`
The dashboard server login user name, if any (for `ftp`, `http`, and `https`).
* [CTest Script](#ctest-script) variable: [`CTEST_DROP_SITE_USER`](../variable/ctest_drop_site_user#variable:CTEST_DROP_SITE_USER "CTEST_DROP_SITE_USER")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `DROP_SITE_USER` if set, else `CTEST_DROP_SITE_USER`
`IsCDash`
Specify whether the dashboard server is [CDash](http://cdash.org/) or an older dashboard server implementation requiring `TriggerSite`.
* [CTest Script](#ctest-script) variable: [`CTEST_DROP_SITE_CDASH`](../variable/ctest_drop_site_cdash#variable:CTEST_DROP_SITE_CDASH "CTEST_DROP_SITE_CDASH")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `CTEST_DROP_SITE_CDASH`
`ScpCommand`
`scp` command-line tool to use when `DropMethod` is `scp`.
* [CTest Script](#ctest-script) variable: [`CTEST_SCP_COMMAND`](../variable/ctest_scp_command#variable:CTEST_SCP_COMMAND "CTEST_SCP_COMMAND")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `SCPCOMMAND`
`Site`
Describe the dashboard client host site with a short string. (Hostname, domain, etc.)
* [CTest Script](#ctest-script) variable: [`CTEST_SITE`](../variable/ctest_site#variable:CTEST_SITE "CTEST_SITE")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `SITE`, initialized by the [`site_name()`](../command/site_name#command:site_name "site_name") command
`TriggerSite`
Legacy option to support older dashboard server implementations. Not used when `IsCDash` is true.
* [CTest Script](#ctest-script) variable: [`CTEST_TRIGGER_SITE`](../variable/ctest_trigger_site#variable:CTEST_TRIGGER_SITE "CTEST_TRIGGER_SITE")
* [`CTest`](../module/ctest#module:CTest "CTest") module variable: `TRIGGER_SITE` if set, else `CTEST_TRIGGER_SITE`
See Also
--------
The following resources are available to get help using CMake:
Home Page
<https://cmake.org>
The primary starting point for learning about CMake.
Frequently Asked Questions
<https://cmake.org/Wiki/CMake_FAQ>
A Wiki is provided containing answers to frequently asked questions.
Online Documentation
<https://cmake.org/documentation>
Links to available documentation may be found on this web page.
Mailing List
<https://cmake.org/mailing-lists>
For help and discussion about using cmake, a mailing list is provided at [[email protected]](mailto:cmake%40cmake.org). The list is member-post-only but one may sign up on the CMake web page. Please first read the full documentation at <https://cmake.org> before posting questions to the list.
| programming_docs |
cmake cmake-developer(7) cmake-developer(7)
==================
* [Introduction](#introduction)
* [Adding Compile Features](#adding-compile-features)
* [Help](#help)
+ [Markup Constructs](#markup-constructs)
+ [CMake Domain](#cmake-domain)
+ [Cross-References](#cross-references)
+ [Style](#style)
- [Style: Section Headers](#style-section-headers)
- [Style: Whitespace](#style-whitespace)
- [Style: Line Length](#style-line-length)
- [Style: Prose](#style-prose)
- [Style: Starting Literal Blocks](#style-starting-literal-blocks)
- [Style: CMake Command Signatures](#style-cmake-command-signatures)
- [Style: Boolean Constants](#style-boolean-constants)
- [Style: Inline Literals](#style-inline-literals)
- [Style: Cross-References](#style-cross-references)
- [Style: Referencing CMake Concepts](#style-referencing-cmake-concepts)
- [Style: Referencing CMake Domain Objects](#style-referencing-cmake-domain-objects)
* [Modules](#modules)
+ [Module Documentation](#module-documentation)
+ [Find Modules](#find-modules)
- [Standard Variable Names](#standard-variable-names)
- [A Sample Find Module](#a-sample-find-module)
Introduction
------------
This manual is intended for reference by developers modifying the CMake source tree itself, and by those authoring externally-maintained modules.
Adding Compile Features
-----------------------
CMake reports an error if a compiler whose features are known does not report support for a particular requested feature. A compiler is considered to have known features if it reports support for at least one feature.
When adding a new compile feature to CMake, it is therefore necessary to list support for the feature for all CompilerIds which already have one or more feature supported, if the new feature is available for any version of the compiler.
When adding the first supported feature to a particular CompilerId, it is necessary to list support for all features known to cmake (See [`CMAKE_C_COMPILE_FEATURES`](../variable/cmake_c_compile_features#variable:CMAKE_C_COMPILE_FEATURES "CMAKE_C_COMPILE_FEATURES") and [`CMAKE_CXX_COMPILE_FEATURES`](../variable/cmake_cxx_compile_features#variable:CMAKE_CXX_COMPILE_FEATURES "CMAKE_CXX_COMPILE_FEATURES") as appropriate), where available for the compiler. Ensure that the `CMAKE_<LANG>_STANDARD_DEFAULT` is set to the computed internal variable `CMAKE_<LANG>_STANDARD_COMPUTED_DEFAULT` for compiler versions which should be supported.
It is sensible to record the features for the most recent version of a particular CompilerId first, and then work backwards. It is sensible to try to create a continuous range of versions of feature releases of the compiler. Gaps in the range indicate incorrect features recorded for intermediate releases.
Generally, features are made available for a particular version if the compiler vendor documents availability of the feature with that version. Note that sometimes partially implemented features appear to be functional in previous releases (such as `cxx_constexpr` in GNU 4.6, though availability is documented in GNU 4.7), and sometimes compiler vendors document availability of features, though supporting infrastructure is not available (such as `__has_feature(cxx_generic_lambdas)` indicating non-availability in Clang 3.4, though it is documented as available, and fixed in Clang 3.5). Similar cases for other compilers and versions need to be investigated when extending CMake to support them.
When a vendor releases a new version of a known compiler which supports a previously unsupported feature, and there are already known features for that compiler, the feature should be listed as supported in CMake for that version of the compiler as soon as reasonably possible.
Standard-specific/compiler-specific variables such `CMAKE_CXX98_COMPILE_FEATURES` are deliberately not documented. They only exist for the compiler-specific implementation of adding the `-std` compile flag for compilers which need that.
Help
----
The `Help` directory contains CMake help manual source files. They are written using the [reStructuredText](http://docutils.sourceforge.net/docs/ref/rst/introduction.html) markup syntax and processed by [Sphinx](http://sphinx-doc.org) to generate the CMake help manuals.
### Markup Constructs
In addition to using Sphinx to generate the CMake help manuals, we also use a C++-implemented document processor to print documents for the `--help-*` command-line help options. It supports a subset of reStructuredText markup. When authoring or modifying documents, please verify that the command-line help looks good in addition to the Sphinx-generated html and man pages.
The command-line help processor supports the following constructs defined by reStructuredText, Sphinx, and a CMake extension to Sphinx.
CMake Domain directives Directives defined in the [CMake Domain](#cmake-domain) for defining CMake documentation objects are printed in command-line help output as if the lines were normal paragraph text with interpretation. CMake Domain interpreted text roles Interpreted text roles defined in the [CMake Domain](#cmake-domain) for cross-referencing CMake documentation objects are replaced by their link text in command-line help output. Other roles are printed literally and not processed.
`code-block directive` Add a literal code block without interpretation. The command-line help processor prints the block content without the leading directive line and with common indentation replaced by one space.
`include directive` Include another document source file. The command-line help processor prints the included document inline with the referencing document.
`literal block after ::` A paragraph ending in `::` followed by a blank line treats the following indented block as literal text without interpretation. The command-line help processor prints the `::` literally and prints the block content with common indentation replaced by one space.
`note directive` Call out a side note. The command-line help processor prints the block content as if the lines were normal paragraph text with interpretation.
`parsed-literal directive` Add a literal block with markup interpretation. The command-line help processor prints the block content without the leading directive line and with common indentation replaced by one space.
`productionlist directive` Render context-free grammar productions. The command-line help processor prints the block content as if the lines were normal paragraph text with interpretation.
`replace directive` Define a `|substitution|` replacement. The command-line help processor requires a substitution replacement to be defined before it is referenced.
`|substitution| reference` Reference a substitution replacement previously defined by the `replace` directive. The command-line help processor performs the substitution and replaces all newlines in the replacement text with spaces.
`toctree directive` Include other document sources in the Table-of-Contents document tree. The command-line help processor prints the referenced documents inline as part of the referencing document. Inline markup constructs not listed above are printed literally in the command-line help output. We prefer to use inline markup constructs that look correct in source form, so avoid use of -escapes in favor of inline literals when possible.
Explicit markup blocks not matching directives listed above are removed from command-line help output. Do not use them, except for plain `..` comments that are removed by Sphinx too.
Note that nested indentation of blocks is not recognized by the command-line help processor. Therefore:
* Explicit markup blocks are recognized only when not indented inside other blocks.
* Literal blocks after paragraphs ending in `::` but not at the top indentation level may consume all indented lines following them.
Try to avoid these cases in practice.
### CMake Domain
CMake adds a [Sphinx Domain](http://sphinx-doc.org/domains.html) called `cmake`, also called the “CMake Domain”. It defines several “object” types for CMake documentation:
`command` A CMake language command.
`generator` A CMake native build system generator. See the [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") command-line tool’s `-G` option.
`manual` A CMake manual page, like this [`cmake-developer(7)`](#manual:cmake-developer(7) "cmake-developer(7)") manual.
`module` A CMake module. See the [`cmake-modules(7)`](cmake-modules.7#manual:cmake-modules(7) "cmake-modules(7)") manual and the [`include()`](../command/include#command:include "include") command.
`policy` A CMake policy. See the [`cmake-policies(7)`](cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") manual and the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command.
`prop_cache, prop_dir, prop_gbl, prop_sf, prop_inst, prop_test, prop_tgt` A CMake cache, directory, global, source file, installed file, test, or target property, respectively. See the [`cmake-properties(7)`](cmake-properties.7#manual:cmake-properties(7) "cmake-properties(7)") manual and the [`set_property()`](../command/set_property#command:set_property "set_property") command.
`variable` A CMake language variable. See the [`cmake-variables(7)`](cmake-variables.7#manual:cmake-variables(7) "cmake-variables(7)") manual and the [`set()`](../command/set#command:set "set") command. Documentation objects in the CMake Domain come from two sources. First, the CMake extension to Sphinx transforms every document named with the form `Help/<type>/<file-name>.rst` to a domain object with type `<type>`. The object name is extracted from the document title, which is expected to be of the form:
```
<object-name>
-------------
```
and to appear at or near the top of the `.rst` file before any other lines starting in a letter, digit, or `<`. If no such title appears literally in the `.rst` file, the object name is the `<file-name>`. If a title does appear, it is expected that `<file-name>` is equal to `<object-name>` with any `<` and `>` characters removed.
Second, the CMake Domain provides directives to define objects inside other documents:
```
.. command:: <command-name>
This indented block documents <command-name>.
.. variable:: <variable-name>
This indented block documents <variable-name>.
```
Object types for which no directive is available must be defined using the first approach above.
### Cross-References
Sphinx uses reStructuredText interpreted text roles to provide cross-reference syntax. The [CMake Domain](#cmake-domain) provides for each domain object type a role of the same name to cross-reference it. CMake Domain roles are inline markup of the forms:
```
:type:`name`
:type:`text <name>`
```
where `type` is the domain object type and `name` is the domain object name. In the first form the link text will be `name` (or `name()` if the type is `command`) and in the second form the link text will be the explicit `text`. For example, the code:
```
* The :command:`list` command.
* The :command:`list(APPEND)` sub-command.
* The :command:`list() command <list>`.
* The :command:`list(APPEND) sub-command <list>`.
* The :variable:`CMAKE_VERSION` variable.
* The :prop_tgt:`OUTPUT_NAME_<CONFIG>` target property.
```
produces:
* The [`list()`](../command/list#command:list "list") command.
* The [`list(APPEND)`](../command/list#command:list "list") sub-command.
* The [`list() command`](../command/list#command:list "list").
* The [`list(APPEND) sub-command`](../command/list#command:list "list").
* The [`CMAKE_VERSION`](../variable/cmake_version#variable:CMAKE_VERSION "CMAKE_VERSION") variable.
* The [`OUTPUT_NAME_<CONFIG>`](# "OUTPUT_NAME_<CONFIG>") target property.
Note that CMake Domain roles differ from Sphinx and reStructuredText convention in that the form `a<b>`, without a space preceding `<`, is interpreted as a name instead of link text with an explicit target. This is necessary because we use `<placeholders>` frequently in object names like `OUTPUT_NAME_<CONFIG>`. The form `a <b>`, with a space preceding `<`, is still interpreted as a link text with an explicit target.
### Style
#### Style: Section Headers
When marking section titles, make the section decoration line as long as the title text. Use only a line below the title, not above. For example:
```
Title Text
----------
```
Capitalize the first letter of each non-minor word in the title.
The section header underline character hierarchy is
* `#`: Manual group (part) in the master document
* `*`: Manual (chapter) title
* `=`: Section within a manual
* `-`: Subsection or [CMake Domain](#cmake-domain) object document title
* `^`: Subsubsection or [CMake Domain](#cmake-domain) object document section
* `"`: Paragraph or [CMake Domain](#cmake-domain) object document subsection
#### Style: Whitespace
Use two spaces for indentation. Use two spaces between sentences in prose.
#### Style: Line Length
Prefer to restrict the width of lines to 75-80 columns. This is not a hard restriction, but writing new paragraphs wrapped at 75 columns allows space for adding minor content without significant re-wrapping of content.
#### Style: Prose
Use American English spellings in prose.
#### Style: Starting Literal Blocks
Prefer to mark the start of literal blocks with `::` at the end of the preceding paragraph. In cases where the following block gets a `code-block` marker, put a single `:` at the end of the preceding paragraph.
#### Style: CMake Command Signatures
Command signatures should be marked up as plain literal blocks, not as cmake `code-blocks`.
Signatures are separated from preceding content by a section header. That is, use:
```
... preceding paragraph.
Normal Libraries
^^^^^^^^^^^^^^^^
::
add_library(<lib> ...)
This signature is used for ...
```
Signatures of commands should wrap optional parts with square brackets, and should mark list of optional arguments with an ellipsis (`...`). Elements of the signature which are specified by the user should be specified with angle brackets, and may be referred to in prose using `inline-literal` syntax.
#### Style: Boolean Constants
Use “`OFF`” and “`ON`” for boolean values which can be modified by the user, such as [`POSITION_INDEPENDENT_CODE`](../prop_tgt/position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE"). Such properties may be “enabled” and “disabled”. Use “`True`” and “`False`” for inherent values which can’t be modified after being set, such as the [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") property of a build target.
#### Style: Inline Literals
Mark up references to keywords in signatures, file names, and other technical terms with `inline-literal` syntax, for example:
```
If ``WIN32`` is used with :command:`add_executable`, the
:prop_tgt:`WIN32_EXECUTABLE` target property is enabled. That command
creates the file ``<name>.exe`` on Windows.
```
#### Style: Cross-References
Mark up linkable references as links, including repeats. An alternative, which is used by wikipedia (<http://en.wikipedia.org/wiki/WP:REPEATLINK>), is to link to a reference only once per article. That style is not used in CMake documentation.
#### Style: Referencing CMake Concepts
If referring to a concept which corresponds to a property, and that concept is described in a high-level manual, prefer to link to the manual section instead of the property. For example:
```
This command creates an :ref:`Imported Target <Imported Targets>`.
```
instead of:
```
This command creates an :prop_tgt:`IMPORTED` target.
```
The latter should be used only when referring specifically to the property.
References to manual sections are not automatically created by creating a section, but code such as:
```
.. _`Imported Targets`:
```
creates a suitable anchor. Use an anchor name which matches the name of the corresponding section. Refer to the anchor using a cross-reference with specified text.
Imported Targets need the `IMPORTED` term marked up with care in particular because the term may refer to a command keyword (`IMPORTED`), a target property ([`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED")), or a concept ([Imported Targets](cmake-buildsystem.7#imported-targets)).
Where a property, command or variable is related conceptually to others, by for example, being related to the buildsystem description, generator expressions or Qt, each relevant property, command or variable should link to the primary manual, which provides high-level information. Only particular information relating to the command should be in the documentation of the command.
#### Style: Referencing CMake Domain Objects
When referring to [CMake Domain](#cmake-domain) objects such as properties, variables, commands etc, prefer to link to the target object and follow that with the type of object it is. For example:
```
Set the :prop_tgt:`AUTOMOC` target property to ``ON``.
```
Instead of
```
Set the target property :prop_tgt:`AUTOMOC` to ``ON``.
```
The `policy` directive is an exception, and the type us usually referred to before the link:
```
If policy :prop_tgt:`CMP0022` is set to ``NEW`` the behavior is ...
```
However, markup self-references with `inline-literal` syntax. For example, within the [`add_executable()`](../command/add_executable#command:add_executable "add_executable") command documentation, use
```
``add_executable``
```
not
```
:command:`add_executable`
```
which is used elsewhere.
Modules
-------
The `Modules` directory contains CMake-language `.cmake` module files.
### Module Documentation
To document CMake module `Modules/<module-name>.cmake`, modify `Help/manual/cmake-modules.7.rst` to reference the module in the `toctree` directive, in sorted order, as:
```
/module/<module-name>
```
Then add the module document file `Help/module/<module-name>.rst` containing just the line:
```
.. cmake-module:: ../../Modules/<module-name>.cmake
```
The `cmake-module` directive will scan the module file to extract reStructuredText markup from comment blocks that start in `.rst:`. At the top of `Modules/<module-name>.cmake`, begin with the following license notice:
```
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
```
After this notice, add a *BLANK* line. Then, add documentation using a [Line Comment](cmake-language.7#line-comment) block of the form:
```
#.rst:
# <module-name>
# -------------
#
# <reStructuredText documentation of module>
```
or a [Bracket Comment](cmake-language.7#bracket-comment) of the form:
```
#[[.rst:
<module-name>
-------------
<reStructuredText documentation of module>
#]]
```
Any number of `=` may be used in the opening and closing brackets as long as they match. Content on the line containing the closing bracket is excluded if and only if the line starts in `#`.
Additional such `.rst:` comments may appear anywhere in the module file. All such comments must start with `#` in the first column.
For example, a `Modules/Findxxx.cmake` module may contain:
```
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#.rst:
# FindXxx
# -------
#
# This is a cool module.
# This module does really cool stuff.
# It can do even more than you think.
#
# It even needs two paragraphs to tell you about it.
# And it defines the following variables:
#
# * VAR_COOL: this is great isn't it?
# * VAR_REALLY_COOL: cool right?
<code>
#[========================================[.rst:
.. command:: xxx_do_something
This command does something for Xxx::
xxx_do_something(some arguments)
#]========================================]
macro(xxx_do_something)
<code>
endmacro()
```
Test the documentation formatting by running `cmake --help-module <module-name>`, and also by enabling the `SPHINX_HTML` and `SPHINX_MAN` options to build the documentation. Edit the comments until generated documentation looks satisfactory. To have a .cmake file in this directory NOT show up in the modules documentation, simply leave out the `Help/module/<module-name>.rst` file and the `Help/manual/cmake-modules.7.rst` toctree entry.
### Find Modules
A “find module” is a `Modules/Find<package>.cmake` file to be loaded by the [`find_package()`](../command/find_package#command:find_package "find_package") command when invoked for `<package>`.
The primary task of a find module is to determine whether a package exists on the system, set the `<package>_FOUND` variable to reflect this and provide any variables, macros and imported targets required to use the package. A find module is useful in cases where an upstream library does not provide a [config file package](cmake-packages.7#config-file-packages).
The traditional approach is to use variables for everything, including libraries and executables: see the [Standard Variable Names](#standard-variable-names) section below. This is what most of the existing find modules provided by CMake do.
The more modern approach is to behave as much like [config file packages](cmake-packages.7#config-file-packages) files as possible, by providing [imported target](cmake-buildsystem.7#imported-targets). This has the advantage of propagating [Transitive Usage Requirements](cmake-buildsystem.7#target-usage-requirements) to consumers.
In either case (or even when providing both variables and imported targets), find modules should provide backwards compatibility with old versions that had the same name.
A FindFoo.cmake module will typically be loaded by the command:
```
find_package(Foo [major[.minor[.patch[.tweak]]]]
[EXACT] [QUIET] [REQUIRED]
[[COMPONENTS] [components...]]
[OPTIONAL_COMPONENTS components...]
[NO_POLICY_SCOPE])
```
See the [`find_package()`](../command/find_package#command:find_package "find_package") documentation for details on what variables are set for the find module. Most of these are dealt with by using [`FindPackageHandleStandardArgs`](../module/findpackagehandlestandardargs#module:FindPackageHandleStandardArgs "FindPackageHandleStandardArgs").
Briefly, the module should only locate versions of the package compatible with the requested version, as described by the `Foo_FIND_VERSION` family of variables. If `Foo_FIND_QUIETLY` is set to true, it should avoid printing messages, including anything complaining about the package not being found. If `Foo_FIND_REQUIRED` is set to true, the module should issue a `FATAL_ERROR` if the package cannot be found. If neither are set to true, it should print a non-fatal message if it cannot find the package.
Packages that find multiple semi-independent parts (like bundles of libraries) should search for the components listed in `Foo_FIND_COMPONENTS` if it is set , and only set `Foo_FOUND` to true if for each searched-for component `<c>` that was not found, `Foo_FIND_REQUIRED_<c>` is not set to true. The `HANDLE_COMPONENTS` argument of `find_package_handle_standard_args()` can be used to implement this.
If `Foo_FIND_COMPONENTS` is not set, which modules are searched for and required is up to the find module, but should be documented.
For internal implementation, it is a generally accepted convention that variables starting with underscore are for temporary use only.
Like all modules, find modules should be properly documented. To add a module to the CMake documentation, follow the steps in the [Module Documentation](#module-documentation) section above.
#### Standard Variable Names
For a `FindXxx.cmake` module that takes the approach of setting variables (either instead of or in addition to creating imported targets), the following variable names should be used to keep things consistent between find modules. Note that all variables start with `Xxx_` to make sure they do not interfere with other find modules; the same consideration applies to macros, functions and imported targets.
`Xxx_INCLUDE_DIRS` The final set of include directories listed in one variable for use by client code. This should not be a cache entry.
`Xxx_LIBRARIES` The libraries to link against to use Xxx. These should include full paths. This should not be a cache entry.
`Xxx_DEFINITIONS` Definitions to use when compiling code that uses Xxx. This really shouldn’t include options such as `-DHAS_JPEG` that a client source-code file uses to decide whether to `#include <jpeg.h>`
`Xxx_EXECUTABLE` Where to find the Xxx tool.
`Xxx_Yyy_EXECUTABLE` Where to find the Yyy tool that comes with Xxx.
`Xxx_LIBRARY_DIRS` Optionally, the final set of library directories listed in one variable for use by client code. This should not be a cache entry.
`Xxx_ROOT_DIR` Where to find the base directory of Xxx.
`Xxx_VERSION_Yy` Expect Version Yy if true. Make sure at most one of these is ever true.
`Xxx_WRAP_Yy` If False, do not try to use the relevant CMake wrapping command.
`Xxx_Yy_FOUND` If False, optional Yy part of Xxx system is not available.
`Xxx_FOUND` Set to false, or undefined, if we haven’t found, or don’t want to use Xxx.
`Xxx_NOT_FOUND_MESSAGE` Should be set by config-files in the case that it has set `Xxx_FOUND` to FALSE. The contained message will be printed by the [`find_package()`](../command/find_package#command:find_package "find_package") command and by `find_package_handle_standard_args()` to inform the user about the problem.
`Xxx_RUNTIME_LIBRARY_DIRS` Optionally, the runtime library search path for use when running an executable linked to shared libraries. The list should be used by user code to create the `PATH` on windows or `LD_LIBRARY_PATH` on UNIX. This should not be a cache entry.
`Xxx_VERSION` The full version string of the package found, if any. Note that many existing modules provide `Xxx_VERSION_STRING` instead.
`Xxx_VERSION_MAJOR` The major version of the package found, if any.
`Xxx_VERSION_MINOR` The minor version of the package found, if any.
`Xxx_VERSION_PATCH` The patch version of the package found, if any. The following names should not usually be used in CMakeLists.txt files, but are typically cache variables for users to edit and control the behaviour of find modules (like entering the path to a library manually)
`Xxx_LIBRARY` The path of the Xxx library (as used with [`find_library()`](../command/find_library#command:find_library "find_library"), for example).
`Xxx_Yy_LIBRARY` The path of the Yy library that is part of the Xxx system. It may or may not be required to use Xxx.
`Xxx_INCLUDE_DIR` Where to find headers for using the Xxx library.
`Xxx_Yy_INCLUDE_DIR` Where to find headers for using the Yy library of the Xxx system. To prevent users being overwhelmed with settings to configure, try to keep as many options as possible out of the cache, leaving at least one option which can be used to disable use of the module, or locate a not-found library (e.g. `Xxx_ROOT_DIR`). For the same reason, mark most cache options as advanced. For packages which provide both debug and release binaries, it is common to create cache variables with a `_LIBRARY_<CONFIG>` suffix, such as `Foo_LIBRARY_RELEASE` and `Foo_LIBRARY_DEBUG`.
While these are the standard variable names, you should provide backwards compatibility for any old names that were actually in use. Make sure you comment them as deprecated, so that no-one starts using them.
#### A Sample Find Module
We will describe how to create a simple find module for a library `Foo`.
The first thing that is needed is a license notice.
```
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
```
Next we need module documentation. CMake’s documentation system requires you to follow the license notice with a blank line and then with a documentation marker and the name of the module. You should follow this with a simple statement of what the module does.
```
#.rst:
# FindFoo
# -------
#
# Finds the Foo library
#
```
More description may be required for some packages. If there are caveats or other details users of the module should be aware of, you can add further paragraphs below this. Then you need to document what variables and imported targets are set by the module, such as
```
# This will define the following variables::
#
# Foo_FOUND - True if the system has the Foo library
# Foo_VERSION - The version of the Foo library which was found
#
# and the following imported targets::
#
# Foo::Foo - The Foo library
```
If the package provides any macros, they should be listed here, but can be documented where they are defined. See the [Module Documentation](#module-documentation) section above for more details.
Now the actual libraries and so on have to be found. The code here will obviously vary from module to module (dealing with that, after all, is the point of find modules), but there tends to be a common pattern for libraries.
First, we try to use `pkg-config` to find the library. Note that we cannot rely on this, as it may not be available, but it provides a good starting point.
```
find_package(PkgConfig)
pkg_check_modules(PC_Foo QUIET Foo)
```
This should define some variables starting `PC_Foo_` that contain the information from the `Foo.pc` file.
Now we need to find the libraries and include files; we use the information from `pkg-config` to provide hints to CMake about where to look.
```
find_path(Foo_INCLUDE_DIR
NAMES foo.h
PATHS ${PC_Foo_INCLUDE_DIRS}
PATH_SUFFIXES Foo
)
find_library(Foo_LIBRARY
NAMES foo
PATHS ${PC_Foo_LIBRARY_DIRS}
)
```
If you have a good way of getting the version (from a header file, for example), you can use that information to set `Foo_VERSION` (although note that find modules have traditionally used `Foo_VERSION_STRING`, so you may want to set both). Otherwise, attempt to use the information from `pkg-config`
```
set(Foo_VERSION ${PC_Foo_VERSION})
```
Now we can use [`FindPackageHandleStandardArgs`](../module/findpackagehandlestandardargs#module:FindPackageHandleStandardArgs "FindPackageHandleStandardArgs") to do most of the rest of the work for us
```
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Foo
FOUND_VAR Foo_FOUND
REQUIRED_VARS
Foo_LIBRARY
Foo_INCLUDE_DIR
VERSION_VAR Foo_VERSION
)
```
This will check that the `REQUIRED_VARS` contain values (that do not end in `-NOTFOUND`) and set `Foo_FOUND` appropriately. It will also cache those values. If `Foo_VERSION` is set, and a required version was passed to [`find_package()`](../command/find_package#command:find_package "find_package"), it will check the requested version against the one in `Foo_VERSION`. It will also print messages as appropriate; note that if the package was found, it will print the contents of the first required variable to indicate where it was found.
At this point, we have to provide a way for users of the find module to link to the library or libraries that were found. There are two approaches, as discussed in the [Find Modules](#find-modules) section above. The traditional variable approach looks like
```
if(Foo_FOUND)
set(Foo_LIBRARIES ${Foo_LIBRARY})
set(Foo_INCLUDE_DIRS ${Foo_INCLUDE_DIR})
set(Foo_DEFINITIONS ${PC_Foo_CFLAGS_OTHER})
endif()
```
If more than one library was found, all of them should be included in these variables (see the [Standard Variable Names](#standard-variable-names) section for more information).
When providing imported targets, these should be namespaced (hence the `Foo::` prefix); CMake will recognize that values passed to [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") that contain `::` in their name are supposed to be imported targets (rather than just library names), and will produce appropriate diagnostic messages if that target does not exist (see policy [`CMP0028`](../policy/cmp0028#policy:CMP0028 "CMP0028")).
```
if(Foo_FOUND AND NOT TARGET Foo::Foo)
add_library(Foo::Foo UNKNOWN IMPORTED)
set_target_properties(Foo::Foo PROPERTIES
IMPORTED_LOCATION "${Foo_LIBRARY}"
INTERFACE_COMPILE_OPTIONS "${PC_Foo_CFLAGS_OTHER}"
INTERFACE_INCLUDE_DIRECTORIES "${Foo_INCLUDE_DIR}"
)
endif()
```
One thing to note about this is that the `INTERFACE_INCLUDE_DIRECTORIES` and similar properties should only contain information about the target itself, and not any of its dependencies. Instead, those dependencies should also be targets, and CMake should be told that they are dependencies of this target. CMake will then combine all the necessary information automatically.
The type of the [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target created in the [`add_library()`](../command/add_library#command:add_library "add_library") command can always be specified as `UNKNOWN` type. This simplifies the code in cases where static or shared variants may be found, and CMake will determine the type by inspecting the files.
If the library is available with multiple configurations, the [`IMPORTED_CONFIGURATIONS`](../prop_tgt/imported_configurations#prop_tgt:IMPORTED_CONFIGURATIONS "IMPORTED_CONFIGURATIONS") target property should also be populated:
```
if(Foo_FOUND)
if (NOT TARGET Foo::Foo)
add_library(Foo::Foo UNKNOWN IMPORTED)
endif()
if (Foo_LIBRARY_RELEASE)
set_property(TARGET Foo::Foo APPEND PROPERTY
IMPORTED_CONFIGURATIONS RELEASE
)
set_target_properties(Foo::Foo PROPERTIES
IMPORTED_LOCATION_RELEASE "${Foo_LIBRARY_RELEASE}"
)
endif()
if (Foo_LIBRARY_DEBUG)
set_property(TARGET Foo::Foo APPEND PROPERTY
IMPORTED_CONFIGURATIONS DEBUG
)
set_target_properties(Foo::Foo PROPERTIES
IMPORTED_LOCATION_DEBUG "${Foo_LIBRARY_DEBUG}"
)
endif()
set_target_properties(Foo::Foo PROPERTIES
INTERFACE_COMPILE_OPTIONS "${PC_Foo_CFLAGS_OTHER}"
INTERFACE_INCLUDE_DIRECTORIES "${Foo_INCLUDE_DIR}"
)
endif()
```
The `RELEASE` variant should be listed first in the property so that that variant is chosen if the user uses a configuration which is not an exact match for any listed `IMPORTED_CONFIGURATIONS`.
Most of the cache variables should be hidden in the `ccmake` interface unless the user explicitly asks to edit them.
```
mark_as_advanced(
Foo_INCLUDE_DIR
Foo_LIBRARY
)
```
If this module replaces an older version, you should set compatibility variables to cause the least disruption possible.
```
# compatibility variables
set(Foo_VERSION_STRING ${Foo_VERSION})
```
| programming_docs |
cmake ccmake(1) ccmake(1)
=========
Synopsis
--------
```
ccmake [<options>] (<path-to-source> | <path-to-existing-build>)
```
Description
-----------
The “ccmake” executable is the CMake curses interface. Project configuration settings may be specified interactively through this GUI. Brief instructions are provided at the bottom of the terminal when the program is running.
CMake is a cross-platform build system generator. Projects specify their build process with platform-independent CMake listfiles included in each directory of a source tree with the name CMakeLists.txt. Users build a project by using CMake to generate a build system for a native tool on their platform.
Options
-------
`-C <initial-cache>`
Pre-load a script to populate the cache.
When cmake is first run in an empty build tree, it creates a CMakeCache.txt file and populates it with customizable settings for the project. This option may be used to specify a file from which to load cache entries before the first pass through the project’s cmake listfiles. The loaded entries take priority over the project’s default values. The given file should be a CMake script containing SET commands that use the CACHE option, not a cache-format file.
`-D <var>:<type>=<value>, -D <var>=<value>`
Create a cmake cache entry.
When cmake is first run in an empty build tree, it creates a CMakeCache.txt file and populates it with customizable settings for the project. This option may be used to specify a setting that takes priority over the project’s default value. The option may be repeated for as many cache entries as desired.
If the `:<type>` portion is given it must be one of the types specified by the [`set()`](../command/set#command:set "set") command documentation for its `CACHE` signature. If the `:<type>` portion is omitted the entry will be created with no type if it does not exist with a type already. If a command in the project sets the type to `PATH` or `FILEPATH` then the `<value>` will be converted to an absolute path.
This option may also be given as a single argument: `-D<var>:<type>=<value>` or `-D<var>=<value>`.
`-U <globbing_expr>`
Remove matching entries from CMake cache.
This option may be used to remove one or more variables from the CMakeCache.txt file, globbing expressions using \* and ? are supported. The option may be repeated for as many cache entries as desired.
Use with care, you can make your CMakeCache.txt non-working.
`-G <generator-name>`
Specify a build system generator.
CMake may support multiple native build systems on certain platforms. A generator is responsible for generating a particular build system. Possible generator names are specified in the [`cmake-generators(7)`](cmake-generators.7#manual:cmake-generators(7) "cmake-generators(7)") manual.
`-T <toolset-spec>`
Toolset specification for the generator, if supported.
Some CMake generators support a toolset specification to tell the native build system how to choose a compiler. See the [`CMAKE_GENERATOR_TOOLSET`](../variable/cmake_generator_toolset#variable:CMAKE_GENERATOR_TOOLSET "CMAKE_GENERATOR_TOOLSET") variable for details.
`-A <platform-name>`
Specify platform name if supported by generator.
Some CMake generators support a platform name to be given to the native build system to choose a compiler or SDK. See the [`CMAKE_GENERATOR_PLATFORM`](../variable/cmake_generator_platform#variable:CMAKE_GENERATOR_PLATFORM "CMAKE_GENERATOR_PLATFORM") variable for details.
`-Wno-dev`
Suppress developer warnings.
Suppress warnings that are meant for the author of the CMakeLists.txt files. By default this will also turn off deprecation warnings.
`-Wdev`
Enable developer warnings.
Enable warnings that are meant for the author of the CMakeLists.txt files. By default this will also turn on deprecation warnings.
`-Werror=dev`
Make developer warnings errors.
Make warnings that are meant for the author of the CMakeLists.txt files errors. By default this will also turn on deprecated warnings as errors.
`-Wno-error=dev`
Make developer warnings not errors.
Make warnings that are meant for the author of the CMakeLists.txt files not errors. By default this will also turn off deprecated warnings as errors.
`-Wdeprecated`
Enable deprecated functionality warnings.
Enable warnings for usage of deprecated functionality, that are meant for the author of the CMakeLists.txt files.
`-Wno-deprecated`
Suppress deprecated functionality warnings.
Suppress warnings for usage of deprecated functionality, that are meant for the author of the CMakeLists.txt files.
`-Werror=deprecated`
Make deprecated macro and function warnings errors.
Make warnings for usage of deprecated macros and functions, that are meant for the author of the CMakeLists.txt files, errors.
`-Wno-error=deprecated`
Make deprecated macro and function warnings not errors.
Make warnings for usage of deprecated macros and functions, that are meant for the author of the CMakeLists.txt files, not errors.
`--help,-help,-usage,-h,-H,/?`
Print usage information and exit.
Usage describes the basic command line interface and its options.
`--version,-version,/V [<f>]`
Show program name/version banner and exit.
If a file is specified, the version is written into it. The help is printed to a named <f>ile if given.
`--help-full [<f>]`
Print all help manuals and exit.
All manuals are printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-manual <man> [<f>]`
Print one help manual and exit.
The specified manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-manual-list [<f>]`
List help manuals available and exit.
The list contains all manuals for which help may be obtained by using the `--help-manual` option followed by a manual name. The help is printed to a named <f>ile if given.
`--help-command <cmd> [<f>]`
Print help for one command and exit.
The [`cmake-commands(7)`](cmake-commands.7#manual:cmake-commands(7) "cmake-commands(7)") manual entry for `<cmd>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-command-list [<f>]`
List commands with help available and exit.
The list contains all commands for which help may be obtained by using the `--help-command` option followed by a command name. The help is printed to a named <f>ile if given.
`--help-commands [<f>]`
Print cmake-commands manual and exit.
The [`cmake-commands(7)`](cmake-commands.7#manual:cmake-commands(7) "cmake-commands(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-module <mod> [<f>]`
Print help for one module and exit.
The [`cmake-modules(7)`](cmake-modules.7#manual:cmake-modules(7) "cmake-modules(7)") manual entry for `<mod>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-module-list [<f>]`
List modules with help available and exit.
The list contains all modules for which help may be obtained by using the `--help-module` option followed by a module name. The help is printed to a named <f>ile if given.
`--help-modules [<f>]`
Print cmake-modules manual and exit.
The [`cmake-modules(7)`](cmake-modules.7#manual:cmake-modules(7) "cmake-modules(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-policy <cmp> [<f>]`
Print help for one policy and exit.
The [`cmake-policies(7)`](cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") manual entry for `<cmp>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-policy-list [<f>]`
List policies with help available and exit.
The list contains all policies for which help may be obtained by using the `--help-policy` option followed by a policy name. The help is printed to a named <f>ile if given.
`--help-policies [<f>]`
Print cmake-policies manual and exit.
The [`cmake-policies(7)`](cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-property <prop> [<f>]`
Print help for one property and exit.
The [`cmake-properties(7)`](cmake-properties.7#manual:cmake-properties(7) "cmake-properties(7)") manual entries for `<prop>` are printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-property-list [<f>]`
List properties with help available and exit.
The list contains all properties for which help may be obtained by using the `--help-property` option followed by a property name. The help is printed to a named <f>ile if given.
`--help-properties [<f>]`
Print cmake-properties manual and exit.
The [`cmake-properties(7)`](cmake-properties.7#manual:cmake-properties(7) "cmake-properties(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-variable <var> [<f>]`
Print help for one variable and exit.
The [`cmake-variables(7)`](cmake-variables.7#manual:cmake-variables(7) "cmake-variables(7)") manual entry for `<var>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-variable-list [<f>]`
List variables with help available and exit.
The list contains all variables for which help may be obtained by using the `--help-variable` option followed by a variable name. The help is printed to a named <f>ile if given.
`--help-variables [<f>]`
Print cmake-variables manual and exit.
The [`cmake-variables(7)`](cmake-variables.7#manual:cmake-variables(7) "cmake-variables(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
See Also
--------
The following resources are available to get help using CMake:
Home Page
<https://cmake.org>
The primary starting point for learning about CMake.
Frequently Asked Questions
<https://cmake.org/Wiki/CMake_FAQ>
A Wiki is provided containing answers to frequently asked questions.
Online Documentation
<https://cmake.org/documentation>
Links to available documentation may be found on this web page.
Mailing List
<https://cmake.org/mailing-lists>
For help and discussion about using cmake, a mailing list is provided at [[email protected]](mailto:cmake%40cmake.org). The list is member-post-only but one may sign up on the CMake web page. Please first read the full documentation at <https://cmake.org> before posting questions to the list.
cmake cmake-properties(7) cmake-properties(7)
===================
* [Properties of Global Scope](#properties-of-global-scope)
* [Properties on Directories](#properties-on-directories)
* [Properties on Targets](#properties-on-targets)
* [Properties on Tests](#properties-on-tests)
* [Properties on Source Files](#properties-on-source-files)
* [Properties on Cache Entries](#properties-on-cache-entries)
* [Properties on Installed Files](#properties-on-installed-files)
* [Deprecated Properties on Directories](#deprecated-properties-on-directories)
* [Deprecated Properties on Targets](#deprecated-properties-on-targets)
* [Deprecated Properties on Source Files](#deprecated-properties-on-source-files)
Properties of Global Scope
--------------------------
* [ALLOW\_DUPLICATE\_CUSTOM\_TARGETS](../prop_gbl/allow_duplicate_custom_targets)
* [AUTOGEN\_SOURCE\_GROUP](../prop_gbl/autogen_source_group)
* [AUTOGEN\_TARGETS\_FOLDER](../prop_gbl/autogen_targets_folder)
* [AUTOMOC\_SOURCE\_GROUP](../prop_gbl/automoc_source_group)
* [AUTOMOC\_TARGETS\_FOLDER](../prop_gbl/automoc_targets_folder)
* [AUTORCC\_SOURCE\_GROUP](../prop_gbl/autorcc_source_group)
* [CMAKE\_C\_KNOWN\_FEATURES](../prop_gbl/cmake_c_known_features)
* [CMAKE\_CXX\_KNOWN\_FEATURES](../prop_gbl/cmake_cxx_known_features)
* [DEBUG\_CONFIGURATIONS](../prop_gbl/debug_configurations)
* [DISABLED\_FEATURES](../prop_gbl/disabled_features)
* [ENABLED\_FEATURES](../prop_gbl/enabled_features)
* [ENABLED\_LANGUAGES](../prop_gbl/enabled_languages)
* [FIND\_LIBRARY\_USE\_LIB32\_PATHS](../prop_gbl/find_library_use_lib32_paths)
* [FIND\_LIBRARY\_USE\_LIB64\_PATHS](../prop_gbl/find_library_use_lib64_paths)
* [FIND\_LIBRARY\_USE\_LIBX32\_PATHS](../prop_gbl/find_library_use_libx32_paths)
* [FIND\_LIBRARY\_USE\_OPENBSD\_VERSIONING](../prop_gbl/find_library_use_openbsd_versioning)
* [GENERATOR\_IS\_MULTI\_CONFIG](../prop_gbl/generator_is_multi_config)
* [GLOBAL\_DEPENDS\_DEBUG\_MODE](../prop_gbl/global_depends_debug_mode)
* [GLOBAL\_DEPENDS\_NO\_CYCLES](../prop_gbl/global_depends_no_cycles)
* [IN\_TRY\_COMPILE](../prop_gbl/in_try_compile)
* [PACKAGES\_FOUND](../prop_gbl/packages_found)
* [PACKAGES\_NOT\_FOUND](../prop_gbl/packages_not_found)
* [JOB\_POOLS](../prop_gbl/job_pools)
* [PREDEFINED\_TARGETS\_FOLDER](../prop_gbl/predefined_targets_folder)
* [ECLIPSE\_EXTRA\_NATURES](../prop_gbl/eclipse_extra_natures)
* [REPORT\_UNDEFINED\_PROPERTIES](../prop_gbl/report_undefined_properties)
* [RULE\_LAUNCH\_COMPILE](../prop_gbl/rule_launch_compile)
* [RULE\_LAUNCH\_CUSTOM](../prop_gbl/rule_launch_custom)
* [RULE\_LAUNCH\_LINK](../prop_gbl/rule_launch_link)
* [RULE\_MESSAGES](../prop_gbl/rule_messages)
* [TARGET\_ARCHIVES\_MAY\_BE\_SHARED\_LIBS](../prop_gbl/target_archives_may_be_shared_libs)
* [TARGET\_MESSAGES](../prop_gbl/target_messages)
* [TARGET\_SUPPORTS\_SHARED\_LIBS](../prop_gbl/target_supports_shared_libs)
* [USE\_FOLDERS](../prop_gbl/use_folders)
* [XCODE\_EMIT\_EFFECTIVE\_PLATFORM\_NAME](../prop_gbl/xcode_emit_effective_platform_name)
Properties on Directories
-------------------------
* [ADDITIONAL\_MAKE\_CLEAN\_FILES](../prop_dir/additional_make_clean_files)
* [BINARY\_DIR](../prop_dir/binary_dir)
* [BUILDSYSTEM\_TARGETS](../prop_dir/buildsystem_targets)
* [CACHE\_VARIABLES](../prop_dir/cache_variables)
* [CLEAN\_NO\_CUSTOM](../prop_dir/clean_no_custom)
* [CMAKE\_CONFIGURE\_DEPENDS](../prop_dir/cmake_configure_depends)
* [COMPILE\_DEFINITIONS](../prop_dir/compile_definitions)
* [COMPILE\_OPTIONS](../prop_dir/compile_options)
* [DEFINITIONS](../prop_dir/definitions)
* [EXCLUDE\_FROM\_ALL](../prop_dir/exclude_from_all)
* [IMPLICIT\_DEPENDS\_INCLUDE\_TRANSFORM](../prop_dir/implicit_depends_include_transform)
* [INCLUDE\_DIRECTORIES](../prop_dir/include_directories)
* [INCLUDE\_REGULAR\_EXPRESSION](../prop_dir/include_regular_expression)
* [INTERPROCEDURAL\_OPTIMIZATION\_<CONFIG>](../prop_dir/interprocedural_optimization_config)
* [INTERPROCEDURAL\_OPTIMIZATION](../prop_dir/interprocedural_optimization)
* [LINK\_DIRECTORIES](../prop_dir/link_directories)
* [LISTFILE\_STACK](../prop_dir/listfile_stack)
* [MACROS](../prop_dir/macros)
* [PARENT\_DIRECTORY](../prop_dir/parent_directory)
* [RULE\_LAUNCH\_COMPILE](../prop_dir/rule_launch_compile)
* [RULE\_LAUNCH\_CUSTOM](../prop_dir/rule_launch_custom)
* [RULE\_LAUNCH\_LINK](../prop_dir/rule_launch_link)
* [SOURCE\_DIR](../prop_dir/source_dir)
* [SUBDIRECTORIES](../prop_dir/subdirectories)
* [TEST\_INCLUDE\_FILE](../prop_dir/test_include_file)
* [VARIABLES](../prop_dir/variables)
* [VS\_GLOBAL\_SECTION\_POST\_<section>](../prop_dir/vs_global_section_post_section)
* [VS\_GLOBAL\_SECTION\_PRE\_<section>](../prop_dir/vs_global_section_pre_section)
* [VS\_STARTUP\_PROJECT](../prop_dir/vs_startup_project)
Properties on Targets
---------------------
* [ALIASED\_TARGET](../prop_tgt/aliased_target)
* [ANDROID\_ANT\_ADDITIONAL\_OPTIONS](../prop_tgt/android_ant_additional_options)
* [ANDROID\_API](../prop_tgt/android_api)
* [ANDROID\_API\_MIN](../prop_tgt/android_api_min)
* [ANDROID\_ARCH](../prop_tgt/android_arch)
* [ANDROID\_ASSETS\_DIRECTORIES](../prop_tgt/android_assets_directories)
* [ANDROID\_GUI](../prop_tgt/android_gui)
* [ANDROID\_JAR\_DEPENDENCIES](../prop_tgt/android_jar_dependencies)
* [ANDROID\_JAR\_DIRECTORIES](../prop_tgt/android_jar_directories)
* [ANDROID\_JAVA\_SOURCE\_DIR](../prop_tgt/android_java_source_dir)
* [ANDROID\_NATIVE\_LIB\_DEPENDENCIES](../prop_tgt/android_native_lib_dependencies)
* [ANDROID\_NATIVE\_LIB\_DIRECTORIES](../prop_tgt/android_native_lib_directories)
* [ANDROID\_PROCESS\_MAX](../prop_tgt/android_process_max)
* [ANDROID\_PROGUARD](../prop_tgt/android_proguard)
* [ANDROID\_PROGUARD\_CONFIG\_PATH](../prop_tgt/android_proguard_config_path)
* [ANDROID\_SECURE\_PROPS\_PATH](../prop_tgt/android_secure_props_path)
* [ANDROID\_SKIP\_ANT\_STEP](../prop_tgt/android_skip_ant_step)
* [ANDROID\_STL\_TYPE](../prop_tgt/android_stl_type)
* [ARCHIVE\_OUTPUT\_DIRECTORY\_<CONFIG>](../prop_tgt/archive_output_directory_config)
* [ARCHIVE\_OUTPUT\_DIRECTORY](../prop_tgt/archive_output_directory)
* [ARCHIVE\_OUTPUT\_NAME\_<CONFIG>](../prop_tgt/archive_output_name_config)
* [ARCHIVE\_OUTPUT\_NAME](../prop_tgt/archive_output_name)
* [AUTOGEN\_BUILD\_DIR](../prop_tgt/autogen_build_dir)
* [AUTOGEN\_TARGET\_DEPENDS](../prop_tgt/autogen_target_depends)
* [AUTOMOC\_DEPEND\_FILTERS](../prop_tgt/automoc_depend_filters)
* [Example](../prop_tgt/automoc_depend_filters#example)
* [AUTOMOC\_MOC\_OPTIONS](../prop_tgt/automoc_moc_options)
* [AUTOMOC](../prop_tgt/automoc)
* [AUTOUIC](../prop_tgt/autouic)
* [AUTOUIC\_OPTIONS](../prop_tgt/autouic_options)
* [AUTOUIC\_SEARCH\_PATHS](../prop_tgt/autouic_search_paths)
* [AUTORCC](../prop_tgt/autorcc)
* [AUTORCC\_OPTIONS](../prop_tgt/autorcc_options)
* [BINARY\_DIR](../prop_tgt/binary_dir)
* [BUILD\_RPATH](../prop_tgt/build_rpath)
* [BUILD\_WITH\_INSTALL\_NAME\_DIR](../prop_tgt/build_with_install_name_dir)
* [BUILD\_WITH\_INSTALL\_RPATH](../prop_tgt/build_with_install_rpath)
* [BUNDLE\_EXTENSION](../prop_tgt/bundle_extension)
* [BUNDLE](../prop_tgt/bundle)
* [C\_EXTENSIONS](../prop_tgt/c_extensions)
* [C\_STANDARD](../prop_tgt/c_standard)
* [C\_STANDARD\_REQUIRED](../prop_tgt/c_standard_required)
* [COMPATIBLE\_INTERFACE\_BOOL](../prop_tgt/compatible_interface_bool)
* [COMPATIBLE\_INTERFACE\_NUMBER\_MAX](../prop_tgt/compatible_interface_number_max)
* [COMPATIBLE\_INTERFACE\_NUMBER\_MIN](../prop_tgt/compatible_interface_number_min)
* [COMPATIBLE\_INTERFACE\_STRING](../prop_tgt/compatible_interface_string)
* [COMPILE\_DEFINITIONS](../prop_tgt/compile_definitions)
* [COMPILE\_FEATURES](../prop_tgt/compile_features)
* [COMPILE\_FLAGS](../prop_tgt/compile_flags)
* [COMPILE\_OPTIONS](../prop_tgt/compile_options)
* [COMPILE\_PDB\_NAME](../prop_tgt/compile_pdb_name)
* [COMPILE\_PDB\_NAME\_<CONFIG>](../prop_tgt/compile_pdb_name_config)
* [COMPILE\_PDB\_OUTPUT\_DIRECTORY](../prop_tgt/compile_pdb_output_directory)
* [COMPILE\_PDB\_OUTPUT\_DIRECTORY\_<CONFIG>](../prop_tgt/compile_pdb_output_directory_config)
* [<CONFIG>\_OUTPUT\_NAME](../prop_tgt/config_output_name)
* [<CONFIG>\_POSTFIX](../prop_tgt/config_postfix)
* [CROSSCOMPILING\_EMULATOR](../prop_tgt/crosscompiling_emulator)
* [CUDA\_PTX\_COMPILATION](../prop_tgt/cuda_ptx_compilation)
* [CUDA\_SEPARABLE\_COMPILATION](../prop_tgt/cuda_separable_compilation)
* [CUDA\_RESOLVE\_DEVICE\_SYMBOLS](../prop_tgt/cuda_resolve_device_symbols)
* [CUDA\_EXTENSIONS](../prop_tgt/cuda_extensions)
* [CUDA\_STANDARD](../prop_tgt/cuda_standard)
* [CUDA\_STANDARD\_REQUIRED](../prop_tgt/cuda_standard_required)
* [CXX\_EXTENSIONS](../prop_tgt/cxx_extensions)
* [CXX\_STANDARD](../prop_tgt/cxx_standard)
* [CXX\_STANDARD\_REQUIRED](../prop_tgt/cxx_standard_required)
* [DEBUG\_POSTFIX](../prop_tgt/debug_postfix)
* [DEFINE\_SYMBOL](../prop_tgt/define_symbol)
* [DEPLOYMENT\_REMOTE\_DIRECTORY](../prop_tgt/deployment_remote_directory)
* [EchoString](../prop_tgt/echostring)
* [ENABLE\_EXPORTS](../prop_tgt/enable_exports)
* [EXCLUDE\_FROM\_ALL](../prop_tgt/exclude_from_all)
* [EXCLUDE\_FROM\_DEFAULT\_BUILD\_<CONFIG>](../prop_tgt/exclude_from_default_build_config)
* [EXCLUDE\_FROM\_DEFAULT\_BUILD](../prop_tgt/exclude_from_default_build)
* [EXPORT\_NAME](../prop_tgt/export_name)
* [FOLDER](../prop_tgt/folder)
* [Fortran\_FORMAT](../prop_tgt/fortran_format)
* [Fortran\_MODULE\_DIRECTORY](../prop_tgt/fortran_module_directory)
* [FRAMEWORK](../prop_tgt/framework)
* [FRAMEWORK\_VERSION](../prop_tgt/framework_version)
* [GENERATOR\_FILE\_NAME](../prop_tgt/generator_file_name)
* [GNUtoMS](../prop_tgt/gnutoms)
* [HAS\_CXX](../prop_tgt/has_cxx)
* [IMPLICIT\_DEPENDS\_INCLUDE\_TRANSFORM](../prop_tgt/implicit_depends_include_transform)
* [IMPORTED\_CONFIGURATIONS](../prop_tgt/imported_configurations)
* [IMPORTED\_IMPLIB\_<CONFIG>](../prop_tgt/imported_implib_config)
* [IMPORTED\_IMPLIB](../prop_tgt/imported_implib)
* [IMPORTED\_LIBNAME\_<CONFIG>](../prop_tgt/imported_libname_config)
* [IMPORTED\_LIBNAME](../prop_tgt/imported_libname)
* [IMPORTED\_LINK\_DEPENDENT\_LIBRARIES\_<CONFIG>](../prop_tgt/imported_link_dependent_libraries_config)
* [IMPORTED\_LINK\_DEPENDENT\_LIBRARIES](../prop_tgt/imported_link_dependent_libraries)
* [IMPORTED\_LINK\_INTERFACE\_LANGUAGES\_<CONFIG>](../prop_tgt/imported_link_interface_languages_config)
* [IMPORTED\_LINK\_INTERFACE\_LANGUAGES](../prop_tgt/imported_link_interface_languages)
* [IMPORTED\_LINK\_INTERFACE\_LIBRARIES\_<CONFIG>](../prop_tgt/imported_link_interface_libraries_config)
* [IMPORTED\_LINK\_INTERFACE\_LIBRARIES](../prop_tgt/imported_link_interface_libraries)
* [IMPORTED\_LINK\_INTERFACE\_MULTIPLICITY\_<CONFIG>](../prop_tgt/imported_link_interface_multiplicity_config)
* [IMPORTED\_LINK\_INTERFACE\_MULTIPLICITY](../prop_tgt/imported_link_interface_multiplicity)
* [IMPORTED\_LOCATION\_<CONFIG>](../prop_tgt/imported_location_config)
* [IMPORTED\_LOCATION](../prop_tgt/imported_location)
* [IMPORTED\_NO\_SONAME\_<CONFIG>](../prop_tgt/imported_no_soname_config)
* [IMPORTED\_NO\_SONAME](../prop_tgt/imported_no_soname)
* [IMPORTED\_OBJECTS\_<CONFIG>](../prop_tgt/imported_objects_config)
* [IMPORTED\_OBJECTS](../prop_tgt/imported_objects)
* [IMPORTED](../prop_tgt/imported)
* [IMPORTED\_SONAME\_<CONFIG>](../prop_tgt/imported_soname_config)
* [IMPORTED\_SONAME](../prop_tgt/imported_soname)
* [IMPORT\_PREFIX](../prop_tgt/import_prefix)
* [IMPORT\_SUFFIX](../prop_tgt/import_suffix)
* [INCLUDE\_DIRECTORIES](../prop_tgt/include_directories)
* [INSTALL\_NAME\_DIR](../prop_tgt/install_name_dir)
* [INSTALL\_RPATH](../prop_tgt/install_rpath)
* [INSTALL\_RPATH\_USE\_LINK\_PATH](../prop_tgt/install_rpath_use_link_path)
* [INTERFACE\_AUTOUIC\_OPTIONS](../prop_tgt/interface_autouic_options)
* [INTERFACE\_COMPILE\_DEFINITIONS](../prop_tgt/interface_compile_definitions)
* [INTERFACE\_COMPILE\_FEATURES](../prop_tgt/interface_compile_features)
* [INTERFACE\_COMPILE\_OPTIONS](../prop_tgt/interface_compile_options)
* [INTERFACE\_INCLUDE\_DIRECTORIES](../prop_tgt/interface_include_directories)
* [INTERFACE\_LINK\_LIBRARIES](../prop_tgt/interface_link_libraries)
* [INTERFACE\_POSITION\_INDEPENDENT\_CODE](../prop_tgt/interface_position_independent_code)
* [INTERFACE\_SOURCES](../prop_tgt/interface_sources)
* [INTERFACE\_SYSTEM\_INCLUDE\_DIRECTORIES](../prop_tgt/interface_system_include_directories)
* [INTERPROCEDURAL\_OPTIMIZATION\_<CONFIG>](../prop_tgt/interprocedural_optimization_config)
* [INTERPROCEDURAL\_OPTIMIZATION](../prop_tgt/interprocedural_optimization)
* [IOS\_INSTALL\_COMBINED](../prop_tgt/ios_install_combined)
* [JOB\_POOL\_COMPILE](../prop_tgt/job_pool_compile)
* [JOB\_POOL\_LINK](../prop_tgt/job_pool_link)
* [LABELS](../prop_tgt/labels)
* [<LANG>\_CLANG\_TIDY](../prop_tgt/lang_clang_tidy)
* [<LANG>\_COMPILER\_LAUNCHER](../prop_tgt/lang_compiler_launcher)
* [<LANG>\_CPPLINT](../prop_tgt/lang_cpplint)
* [<LANG>\_INCLUDE\_WHAT\_YOU\_USE](../prop_tgt/lang_include_what_you_use)
* [<LANG>\_VISIBILITY\_PRESET](../prop_tgt/lang_visibility_preset)
* [LIBRARY\_OUTPUT\_DIRECTORY\_<CONFIG>](../prop_tgt/library_output_directory_config)
* [LIBRARY\_OUTPUT\_DIRECTORY](../prop_tgt/library_output_directory)
* [LIBRARY\_OUTPUT\_NAME\_<CONFIG>](../prop_tgt/library_output_name_config)
* [LIBRARY\_OUTPUT\_NAME](../prop_tgt/library_output_name)
* [LINK\_DEPENDS\_NO\_SHARED](../prop_tgt/link_depends_no_shared)
* [LINK\_DEPENDS](../prop_tgt/link_depends)
* [LINKER\_LANGUAGE](../prop_tgt/linker_language)
* [LINK\_FLAGS\_<CONFIG>](../prop_tgt/link_flags_config)
* [LINK\_FLAGS](../prop_tgt/link_flags)
* [LINK\_INTERFACE\_LIBRARIES\_<CONFIG>](../prop_tgt/link_interface_libraries_config)
* [LINK\_INTERFACE\_LIBRARIES](../prop_tgt/link_interface_libraries)
* [LINK\_INTERFACE\_MULTIPLICITY\_<CONFIG>](../prop_tgt/link_interface_multiplicity_config)
* [LINK\_INTERFACE\_MULTIPLICITY](../prop_tgt/link_interface_multiplicity)
* [LINK\_LIBRARIES](../prop_tgt/link_libraries)
* [LINK\_SEARCH\_END\_STATIC](../prop_tgt/link_search_end_static)
* [LINK\_SEARCH\_START\_STATIC](../prop_tgt/link_search_start_static)
* [LINK\_WHAT\_YOU\_USE](../prop_tgt/link_what_you_use)
* [LOCATION\_<CONFIG>](../prop_tgt/location_config)
* [LOCATION](../prop_tgt/location)
* [MACOSX\_BUNDLE\_INFO\_PLIST](../prop_tgt/macosx_bundle_info_plist)
* [MACOSX\_BUNDLE](../prop_tgt/macosx_bundle)
* [MACOSX\_FRAMEWORK\_INFO\_PLIST](../prop_tgt/macosx_framework_info_plist)
* [MACOSX\_RPATH](../prop_tgt/macosx_rpath)
* [MANUALLY\_ADDED\_DEPENDENCIES](../prop_tgt/manually_added_dependencies)
* [MAP\_IMPORTED\_CONFIG\_<CONFIG>](../prop_tgt/map_imported_config_config)
* [NAME](../prop_tgt/name)
* [NO\_SONAME](../prop_tgt/no_soname)
* [NO\_SYSTEM\_FROM\_IMPORTED](../prop_tgt/no_system_from_imported)
* [OSX\_ARCHITECTURES\_<CONFIG>](../prop_tgt/osx_architectures_config)
* [OSX\_ARCHITECTURES](../prop_tgt/osx_architectures)
* [OUTPUT\_NAME\_<CONFIG>](../prop_tgt/output_name_config)
* [OUTPUT\_NAME](../prop_tgt/output_name)
* [PDB\_NAME\_<CONFIG>](../prop_tgt/pdb_name_config)
* [PDB\_NAME](../prop_tgt/pdb_name)
* [PDB\_OUTPUT\_DIRECTORY\_<CONFIG>](../prop_tgt/pdb_output_directory_config)
* [PDB\_OUTPUT\_DIRECTORY](../prop_tgt/pdb_output_directory)
* [POSITION\_INDEPENDENT\_CODE](../prop_tgt/position_independent_code)
* [PREFIX](../prop_tgt/prefix)
* [PRIVATE\_HEADER](../prop_tgt/private_header)
* [PROJECT\_LABEL](../prop_tgt/project_label)
* [PUBLIC\_HEADER](../prop_tgt/public_header)
* [RESOURCE](../prop_tgt/resource)
* [RULE\_LAUNCH\_COMPILE](../prop_tgt/rule_launch_compile)
* [RULE\_LAUNCH\_CUSTOM](../prop_tgt/rule_launch_custom)
* [RULE\_LAUNCH\_LINK](../prop_tgt/rule_launch_link)
* [RUNTIME\_OUTPUT\_DIRECTORY\_<CONFIG>](../prop_tgt/runtime_output_directory_config)
* [RUNTIME\_OUTPUT\_DIRECTORY](../prop_tgt/runtime_output_directory)
* [RUNTIME\_OUTPUT\_NAME\_<CONFIG>](../prop_tgt/runtime_output_name_config)
* [RUNTIME\_OUTPUT\_NAME](../prop_tgt/runtime_output_name)
* [SKIP\_BUILD\_RPATH](../prop_tgt/skip_build_rpath)
* [SOURCE\_DIR](../prop_tgt/source_dir)
* [SOURCES](../prop_tgt/sources)
* [SOVERSION](../prop_tgt/soversion)
* [STATIC\_LIBRARY\_FLAGS\_<CONFIG>](../prop_tgt/static_library_flags_config)
* [STATIC\_LIBRARY\_FLAGS](../prop_tgt/static_library_flags)
* [SUFFIX](../prop_tgt/suffix)
* [TYPE](../prop_tgt/type)
* [VERSION](../prop_tgt/version)
* [VISIBILITY\_INLINES\_HIDDEN](../prop_tgt/visibility_inlines_hidden)
* [VS\_CONFIGURATION\_TYPE](../prop_tgt/vs_configuration_type)
* [VS\_DEBUGGER\_WORKING\_DIRECTORY](../prop_tgt/vs_debugger_working_directory)
* [VS\_DESKTOP\_EXTENSIONS\_VERSION](../prop_tgt/vs_desktop_extensions_version)
* [VS\_DOTNET\_REFERENCE\_<refname>](../prop_tgt/vs_dotnet_reference_refname)
* [VS\_DOTNET\_REFERENCES](../prop_tgt/vs_dotnet_references)
* [VS\_DOTNET\_REFERENCES\_COPY\_LOCAL](../prop_tgt/vs_dotnet_references_copy_local)
* [VS\_DOTNET\_TARGET\_FRAMEWORK\_VERSION](../prop_tgt/vs_dotnet_target_framework_version)
* [VS\_GLOBAL\_KEYWORD](../prop_tgt/vs_global_keyword)
* [VS\_GLOBAL\_PROJECT\_TYPES](../prop_tgt/vs_global_project_types)
* [VS\_GLOBAL\_ROOTNAMESPACE](../prop_tgt/vs_global_rootnamespace)
* [VS\_GLOBAL\_<variable>](../prop_tgt/vs_global_variable)
* [VS\_IOT\_EXTENSIONS\_VERSION](../prop_tgt/vs_iot_extensions_version)
* [VS\_IOT\_STARTUP\_TASK](../prop_tgt/vs_iot_startup_task)
* [VS\_KEYWORD](../prop_tgt/vs_keyword)
* [VS\_MOBILE\_EXTENSIONS\_VERSION](../prop_tgt/vs_mobile_extensions_version)
* [VS\_SCC\_AUXPATH](../prop_tgt/vs_scc_auxpath)
* [VS\_SCC\_LOCALPATH](../prop_tgt/vs_scc_localpath)
* [VS\_SCC\_PROJECTNAME](../prop_tgt/vs_scc_projectname)
* [VS\_SCC\_PROVIDER](../prop_tgt/vs_scc_provider)
* [VS\_SDK\_REFERENCES](../prop_tgt/vs_sdk_references)
* [VS\_USER\_PROPS](../prop_tgt/vs_user_props)
* [VS\_WINDOWS\_TARGET\_PLATFORM\_MIN\_VERSION](../prop_tgt/vs_windows_target_platform_min_version)
* [VS\_WINRT\_COMPONENT](../prop_tgt/vs_winrt_component)
* [VS\_WINRT\_EXTENSIONS](../prop_tgt/vs_winrt_extensions)
* [VS\_WINRT\_REFERENCES](../prop_tgt/vs_winrt_references)
* [WIN32\_EXECUTABLE](../prop_tgt/win32_executable)
* [WINDOWS\_EXPORT\_ALL\_SYMBOLS](../prop_tgt/windows_export_all_symbols)
* [XCODE\_ATTRIBUTE\_<an-attribute>](../prop_tgt/xcode_attribute_an-attribute)
* [XCODE\_EXPLICIT\_FILE\_TYPE](../prop_tgt/xcode_explicit_file_type)
* [XCODE\_PRODUCT\_TYPE](../prop_tgt/xcode_product_type)
* [XCTEST](../prop_tgt/xctest)
Properties on Tests
-------------------
* [ATTACHED\_FILES\_ON\_FAIL](../prop_test/attached_files_on_fail)
* [ATTACHED\_FILES](../prop_test/attached_files)
* [COST](../prop_test/cost)
* [DEPENDS](../prop_test/depends)
* [DISABLED](../prop_test/disabled)
* [ENVIRONMENT](../prop_test/environment)
* [FAIL\_REGULAR\_EXPRESSION](../prop_test/fail_regular_expression)
* [FIXTURES\_CLEANUP](../prop_test/fixtures_cleanup)
* [FIXTURES\_REQUIRED](../prop_test/fixtures_required)
* [FIXTURES\_SETUP](../prop_test/fixtures_setup)
* [LABELS](../prop_test/labels)
* [MEASUREMENT](../prop_test/measurement)
* [PASS\_REGULAR\_EXPRESSION](../prop_test/pass_regular_expression)
* [PROCESSORS](../prop_test/processors)
* [REQUIRED\_FILES](../prop_test/required_files)
* [RESOURCE\_LOCK](../prop_test/resource_lock)
* [RUN\_SERIAL](../prop_test/run_serial)
* [SKIP\_RETURN\_CODE](../prop_test/skip_return_code)
* [TIMEOUT](../prop_test/timeout)
* [TIMEOUT\_AFTER\_MATCH](../prop_test/timeout_after_match)
* [WILL\_FAIL](../prop_test/will_fail)
* [WORKING\_DIRECTORY](../prop_test/working_directory)
Properties on Source Files
--------------------------
* [ABSTRACT](../prop_sf/abstract)
* [AUTOUIC\_OPTIONS](../prop_sf/autouic_options)
* [AUTORCC\_OPTIONS](../prop_sf/autorcc_options)
* [COMPILE\_DEFINITIONS](../prop_sf/compile_definitions)
* [COMPILE\_FLAGS](../prop_sf/compile_flags)
* [EXTERNAL\_OBJECT](../prop_sf/external_object)
* [Fortran\_FORMAT](../prop_sf/fortran_format)
* [GENERATED](../prop_sf/generated)
* [HEADER\_FILE\_ONLY](../prop_sf/header_file_only)
* [KEEP\_EXTENSION](../prop_sf/keep_extension)
* [LABELS](../prop_sf/labels)
* [LANGUAGE](../prop_sf/language)
* [LOCATION](../prop_sf/location)
* [MACOSX\_PACKAGE\_LOCATION](../prop_sf/macosx_package_location)
* [OBJECT\_DEPENDS](../prop_sf/object_depends)
* [OBJECT\_OUTPUTS](../prop_sf/object_outputs)
* [SKIP\_AUTOGEN](../prop_sf/skip_autogen)
* [SKIP\_AUTOMOC](../prop_sf/skip_automoc)
* [SKIP\_AUTORCC](../prop_sf/skip_autorcc)
* [SKIP\_AUTOUIC](../prop_sf/skip_autouic)
* [SYMBOLIC](../prop_sf/symbolic)
* [VS\_COPY\_TO\_OUT\_DIR](../prop_sf/vs_copy_to_out_dir)
* [VS\_CSHARP\_<tagname>](../prop_sf/vs_csharp_tagname)
* [VS\_DEPLOYMENT\_CONTENT](../prop_sf/vs_deployment_content)
* [VS\_DEPLOYMENT\_LOCATION](../prop_sf/vs_deployment_location)
* [VS\_INCLUDE\_IN\_VSIX](../prop_sf/vs_include_in_vsix)
* [VS\_RESOURCE\_GENERATOR](../prop_sf/vs_resource_generator)
* [VS\_SHADER\_ENTRYPOINT](../prop_sf/vs_shader_entrypoint)
* [VS\_SHADER\_FLAGS](../prop_sf/vs_shader_flags)
* [VS\_SHADER\_MODEL](../prop_sf/vs_shader_model)
* [VS\_SHADER\_TYPE](../prop_sf/vs_shader_type)
* [VS\_TOOL\_OVERRIDE](../prop_sf/vs_tool_override)
* [VS\_XAML\_TYPE](../prop_sf/vs_xaml_type)
* [WRAP\_EXCLUDE](../prop_sf/wrap_exclude)
* [XCODE\_EXPLICIT\_FILE\_TYPE](../prop_sf/xcode_explicit_file_type)
* [XCODE\_FILE\_ATTRIBUTES](../prop_sf/xcode_file_attributes)
* [XCODE\_LAST\_KNOWN\_FILE\_TYPE](../prop_sf/xcode_last_known_file_type)
Properties on Cache Entries
---------------------------
* [ADVANCED](../prop_cache/advanced)
* [HELPSTRING](../prop_cache/helpstring)
* [MODIFIED](../prop_cache/modified)
* [STRINGS](../prop_cache/strings)
* [TYPE](../prop_cache/type)
* [VALUE](../prop_cache/value)
Properties on Installed Files
-----------------------------
* [CPACK\_DESKTOP\_SHORTCUTS](../prop_inst/cpack_desktop_shortcuts)
* [CPACK\_NEVER\_OVERWRITE](../prop_inst/cpack_never_overwrite)
* [CPACK\_PERMANENT](../prop_inst/cpack_permanent)
* [CPACK\_START\_MENU\_SHORTCUTS](../prop_inst/cpack_start_menu_shortcuts)
* [CPACK\_STARTUP\_SHORTCUTS](../prop_inst/cpack_startup_shortcuts)
* [CPACK\_WIX\_ACL](../prop_inst/cpack_wix_acl)
Deprecated Properties on Directories
------------------------------------
* [COMPILE\_DEFINITIONS\_<CONFIG>](../prop_dir/compile_definitions_config)
Deprecated Properties on Targets
--------------------------------
* [COMPILE\_DEFINITIONS\_<CONFIG>](../prop_tgt/compile_definitions_config)
* [POST\_INSTALL\_SCRIPT](../prop_tgt/post_install_script)
* [PRE\_INSTALL\_SCRIPT](../prop_tgt/pre_install_script)
Deprecated Properties on Source Files
-------------------------------------
* [COMPILE\_DEFINITIONS\_<CONFIG>](../prop_sf/compile_definitions_config)
| programming_docs |
cmake cmake-commands(7) cmake-commands(7)
=================
* [Scripting Commands](#scripting-commands)
* [Project Commands](#project-commands)
* [CTest Commands](#ctest-commands)
* [Deprecated Commands](#deprecated-commands)
Scripting Commands
------------------
These commands are always available.
* [break](../command/break)
* [cmake\_host\_system\_information](../command/cmake_host_system_information)
* [cmake\_minimum\_required](../command/cmake_minimum_required)
* [cmake\_parse\_arguments](../command/cmake_parse_arguments)
* [cmake\_policy](../command/cmake_policy)
* [configure\_file](../command/configure_file)
* [continue](../command/continue)
* [elseif](../command/elseif)
* [else](../command/else)
* [endforeach](../command/endforeach)
* [endfunction](../command/endfunction)
* [endif](../command/endif)
* [endmacro](../command/endmacro)
* [endwhile](../command/endwhile)
* [execute\_process](../command/execute_process)
* [file](../command/file)
* [find\_file](../command/find_file)
* [find\_library](../command/find_library)
* [find\_package](../command/find_package)
* [find\_path](../command/find_path)
* [find\_program](../command/find_program)
* [foreach](../command/foreach)
* [function](../command/function)
* [get\_cmake\_property](../command/get_cmake_property)
* [get\_directory\_property](../command/get_directory_property)
* [get\_filename\_component](../command/get_filename_component)
* [get\_property](../command/get_property)
* [if](../command/if)
* [include](../command/include)
* [list](../command/list)
* [macro](../command/macro)
* [mark\_as\_advanced](../command/mark_as_advanced)
* [math](../command/math)
* [message](../command/message)
* [option](../command/option)
* [return](../command/return)
* [separate\_arguments](../command/separate_arguments)
* [set\_directory\_properties](../command/set_directory_properties)
* [set\_property](../command/set_property)
* [set](../command/set)
* [site\_name](../command/site_name)
* [string](../command/string)
* [unset](../command/unset)
* [variable\_watch](../command/variable_watch)
* [while](../command/while)
Project Commands
----------------
These commands are available only in CMake projects.
* [add\_compile\_options](../command/add_compile_options)
* [add\_custom\_command](../command/add_custom_command)
* [add\_custom\_target](../command/add_custom_target)
* [add\_definitions](../command/add_definitions)
* [add\_dependencies](../command/add_dependencies)
* [add\_executable](../command/add_executable)
* [add\_library](../command/add_library)
* [add\_subdirectory](../command/add_subdirectory)
* [add\_test](../command/add_test)
* [aux\_source\_directory](../command/aux_source_directory)
* [build\_command](../command/build_command)
* [create\_test\_sourcelist](../command/create_test_sourcelist)
* [define\_property](../command/define_property)
* [enable\_language](../command/enable_language)
* [enable\_testing](../command/enable_testing)
* [export](../command/export)
* [fltk\_wrap\_ui](../command/fltk_wrap_ui)
* [get\_source\_file\_property](../command/get_source_file_property)
* [get\_target\_property](../command/get_target_property)
* [get\_test\_property](../command/get_test_property)
* [include\_directories](../command/include_directories)
* [include\_external\_msproject](../command/include_external_msproject)
* [include\_regular\_expression](../command/include_regular_expression)
* [install](../command/install)
* [link\_directories](../command/link_directories)
* [link\_libraries](../command/link_libraries)
* [load\_cache](../command/load_cache)
* [project](../command/project)
* [qt\_wrap\_cpp](../command/qt_wrap_cpp)
* [qt\_wrap\_ui](../command/qt_wrap_ui)
* [remove\_definitions](../command/remove_definitions)
* [set\_source\_files\_properties](../command/set_source_files_properties)
* [set\_target\_properties](../command/set_target_properties)
* [set\_tests\_properties](../command/set_tests_properties)
* [source\_group](../command/source_group)
* [target\_compile\_definitions](../command/target_compile_definitions)
* [target\_compile\_features](../command/target_compile_features)
* [target\_compile\_options](../command/target_compile_options)
* [target\_include\_directories](../command/target_include_directories)
* [target\_link\_libraries](../command/target_link_libraries)
* [target\_sources](../command/target_sources)
* [try\_compile](../command/try_compile)
* [try\_run](../command/try_run)
CTest Commands
--------------
These commands are available only in CTest scripts.
* [ctest\_build](../command/ctest_build)
* [ctest\_configure](../command/ctest_configure)
* [ctest\_coverage](../command/ctest_coverage)
* [ctest\_empty\_binary\_directory](../command/ctest_empty_binary_directory)
* [ctest\_memcheck](../command/ctest_memcheck)
* [ctest\_read\_custom\_files](../command/ctest_read_custom_files)
* [ctest\_run\_script](../command/ctest_run_script)
* [ctest\_sleep](../command/ctest_sleep)
* [ctest\_start](../command/ctest_start)
* [ctest\_submit](../command/ctest_submit)
* [ctest\_test](../command/ctest_test)
* [ctest\_update](../command/ctest_update)
* [ctest\_upload](../command/ctest_upload)
Deprecated Commands
-------------------
These commands are available only for compatibility with older versions of CMake. Do not use them in new code.
* [build\_name](../command/build_name)
* [exec\_program](../command/exec_program)
* [export\_library\_dependencies](../command/export_library_dependencies)
* [install\_files](../command/install_files)
* [install\_programs](../command/install_programs)
* [install\_targets](../command/install_targets)
* [load\_command](../command/load_command)
* [make\_directory](../command/make_directory)
* [output\_required\_files](../command/output_required_files)
* [remove](../command/remove)
* [subdir\_depends](../command/subdir_depends)
* [subdirs](../command/subdirs)
* [use\_mangled\_mesa](../command/use_mangled_mesa)
* [utility\_source](../command/utility_source)
* [variable\_requires](../command/variable_requires)
* [write\_file](../command/write_file)
cmake cpack(1) cpack(1)
========
Synopsis
--------
```
cpack -G <generator> [<options>]
```
Description
-----------
The “cpack” executable is the CMake packaging program. CMake-generated build trees created for projects that use the INSTALL\_\* commands have packaging support. This program will generate the package.
CMake is a cross-platform build system generator. Projects specify their build process with platform-independent CMake listfiles included in each directory of a source tree with the name CMakeLists.txt. Users build a project by using CMake to generate a build system for a native tool on their platform.
Options
-------
`-G <generator>`
Use the specified generator to generate package.
CPack may support multiple native packaging systems on certain platforms. A generator is responsible for generating input files for particular system and invoking that systems. Possible generator names are specified in the Generators section.
`-C <Configuration>`
Specify the project configuration
This option specifies the configuration that the project was build with, for example ‘Debug’, ‘Release’.
`-D <var>=<value>`
Set a CPack variable.
Set a variable that can be used by the generator.
`--config <config file>`
Specify the config file.
Specify the config file to use to create the package. By default CPackConfig.cmake in the current directory will be used.
`--verbose,-V`
enable verbose output
Run cpack with verbose output.
`--debug`
enable debug output (for CPack developers)
Run cpack with debug output (for CPack developers).
`-P <package name>`
override/define CPACK\_PACKAGE\_NAME
If the package name is not specified on cpack command line thenCPack.cmake defines it as CMAKE\_PROJECT\_NAME
`-R <package version>`
override/define CPACK\_PACKAGE\_VERSION
If version is not specified on cpack command line thenCPack.cmake defines it from CPACK\_PACKAGE\_VERSION\_[MAJOR|MINOR|PATCH]look into CPack.cmake for detail
`-B <package directory>`
override/define CPACK\_PACKAGE\_DIRECTORY
The directory where CPack will be doing its packaging work.The resulting package will be found there. Inside this directoryCPack creates ‘\_CPack\_Packages’ sub-directory which is theCPack temporary directory.
`--vendor <vendor name>`
override/define CPACK\_PACKAGE\_VENDOR
If vendor is not specified on cpack command line (or inside CMakeLists.txt) thenCPack.cmake defines it with a default value
`--help,-help,-usage,-h,-H,/?`
Print usage information and exit.
Usage describes the basic command line interface and its options.
`--version,-version,/V [<f>]`
Show program name/version banner and exit.
If a file is specified, the version is written into it. The help is printed to a named <f>ile if given.
`--help-full [<f>]`
Print all help manuals and exit.
All manuals are printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-manual <man> [<f>]`
Print one help manual and exit.
The specified manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-manual-list [<f>]`
List help manuals available and exit.
The list contains all manuals for which help may be obtained by using the `--help-manual` option followed by a manual name. The help is printed to a named <f>ile if given.
`--help-command <cmd> [<f>]`
Print help for one command and exit.
The [`cmake-commands(7)`](cmake-commands.7#manual:cmake-commands(7) "cmake-commands(7)") manual entry for `<cmd>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-command-list [<f>]`
List commands with help available and exit.
The list contains all commands for which help may be obtained by using the `--help-command` option followed by a command name. The help is printed to a named <f>ile if given.
`--help-commands [<f>]`
Print cmake-commands manual and exit.
The [`cmake-commands(7)`](cmake-commands.7#manual:cmake-commands(7) "cmake-commands(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-module <mod> [<f>]`
Print help for one module and exit.
The [`cmake-modules(7)`](cmake-modules.7#manual:cmake-modules(7) "cmake-modules(7)") manual entry for `<mod>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-module-list [<f>]`
List modules with help available and exit.
The list contains all modules for which help may be obtained by using the `--help-module` option followed by a module name. The help is printed to a named <f>ile if given.
`--help-modules [<f>]`
Print cmake-modules manual and exit.
The [`cmake-modules(7)`](cmake-modules.7#manual:cmake-modules(7) "cmake-modules(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-policy <cmp> [<f>]`
Print help for one policy and exit.
The [`cmake-policies(7)`](cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") manual entry for `<cmp>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-policy-list [<f>]`
List policies with help available and exit.
The list contains all policies for which help may be obtained by using the `--help-policy` option followed by a policy name. The help is printed to a named <f>ile if given.
`--help-policies [<f>]`
Print cmake-policies manual and exit.
The [`cmake-policies(7)`](cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-property <prop> [<f>]`
Print help for one property and exit.
The [`cmake-properties(7)`](cmake-properties.7#manual:cmake-properties(7) "cmake-properties(7)") manual entries for `<prop>` are printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-property-list [<f>]`
List properties with help available and exit.
The list contains all properties for which help may be obtained by using the `--help-property` option followed by a property name. The help is printed to a named <f>ile if given.
`--help-properties [<f>]`
Print cmake-properties manual and exit.
The [`cmake-properties(7)`](cmake-properties.7#manual:cmake-properties(7) "cmake-properties(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-variable <var> [<f>]`
Print help for one variable and exit.
The [`cmake-variables(7)`](cmake-variables.7#manual:cmake-variables(7) "cmake-variables(7)") manual entry for `<var>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-variable-list [<f>]`
List variables with help available and exit.
The list contains all variables for which help may be obtained by using the `--help-variable` option followed by a variable name. The help is printed to a named <f>ile if given.
`--help-variables [<f>]`
Print cmake-variables manual and exit.
The [`cmake-variables(7)`](cmake-variables.7#manual:cmake-variables(7) "cmake-variables(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
See Also
--------
The following resources are available to get help using CMake:
Home Page
<https://cmake.org>
The primary starting point for learning about CMake.
Frequently Asked Questions
<https://cmake.org/Wiki/CMake_FAQ>
A Wiki is provided containing answers to frequently asked questions.
Online Documentation
<https://cmake.org/documentation>
Links to available documentation may be found on this web page.
Mailing List
<https://cmake.org/mailing-lists>
For help and discussion about using cmake, a mailing list is provided at [[email protected]](mailto:cmake%40cmake.org). The list is member-post-only but one may sign up on the CMake web page. Please first read the full documentation at <https://cmake.org> before posting questions to the list.
cmake cmake-toolchains(7) cmake-toolchains(7)
===================
* [Introduction](#introduction)
* [Languages](#languages)
* [Variables and Properties](#variables-and-properties)
* [Toolchain Features](#toolchain-features)
* [Cross Compiling](#cross-compiling)
+ [Cross Compiling for Linux](#cross-compiling-for-linux)
+ [Cross Compiling for the Cray Linux Environment](#cross-compiling-for-the-cray-linux-environment)
+ [Cross Compiling using Clang](#cross-compiling-using-clang)
+ [Cross Compiling for QNX](#cross-compiling-for-qnx)
+ [Cross Compiling for Windows CE](#cross-compiling-for-windows-ce)
+ [Cross Compiling for Windows 10 Universal Applications](#cross-compiling-for-windows-10-universal-applications)
+ [Cross Compiling for Windows Phone](#cross-compiling-for-windows-phone)
+ [Cross Compiling for Windows Store](#cross-compiling-for-windows-store)
+ [Cross Compiling for Android](#cross-compiling-for-android)
- [Cross Compiling for Android with the NDK](#cross-compiling-for-android-with-the-ndk)
- [Cross Compiling for Android with a Standalone Toolchain](#cross-compiling-for-android-with-a-standalone-toolchain)
- [Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio Edition](#cross-compiling-for-android-with-nvidia-nsight-tegra-visual-studio-edition)
Introduction
------------
CMake uses a toolchain of utilities to compile, link libraries and create archives, and other tasks to drive the build. The toolchain utilities available are determined by the languages enabled. In normal builds, CMake automatically determines the toolchain for host builds based on system introspection and defaults. In cross-compiling scenarios, a toolchain file may be specified with information about compiler and utility paths.
Languages
---------
Languages are enabled by the [`project()`](../command/project#command:project "project") command. Language-specific built-in variables, such as [`CMAKE_CXX_COMPILER`](# "CMAKE_<LANG>_COMPILER"), [`CMAKE_CXX_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") etc are set by invoking the [`project()`](../command/project#command:project "project") command. If no project command is in the top-level CMakeLists file, one will be implicitly generated. By default the enabled languages are C and CXX:
```
project(C_Only C)
```
A special value of NONE can also be used with the [`project()`](../command/project#command:project "project") command to enable no languages:
```
project(MyProject NONE)
```
The [`enable_language()`](../command/enable_language#command:enable_language "enable_language") command can be used to enable languages after the [`project()`](../command/project#command:project "project") command:
```
enable_language(CXX)
```
When a language is enabled, CMake finds a compiler for that language, and determines some information, such as the vendor and version of the compiler, the target architecture and bitwidth, the location of corresponding utilities etc.
The [`ENABLED_LANGUAGES`](../prop_gbl/enabled_languages#prop_gbl:ENABLED_LANGUAGES "ENABLED_LANGUAGES") global property contains the languages which are currently enabled.
Variables and Properties
------------------------
Several variables relate to the language components of a toolchain which are enabled. [`CMAKE_<LANG>_COMPILER`](# "CMAKE_<LANG>_COMPILER") is the full path to the compiler used for `<LANG>`. [`CMAKE_<LANG>_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") is the identifier used by CMake for the compiler and [`CMAKE_<LANG>_COMPILER_VERSION`](# "CMAKE_<LANG>_COMPILER_VERSION") is the version of the compiler.
The [`CMAKE_<LANG>_FLAGS`](# "CMAKE_<LANG>_FLAGS") variables and the configuration-specific equivalents contain flags that will be added to the compile command when compiling a file of a particular language.
As the linker is invoked by the compiler driver, CMake needs a way to determine which compiler to use to invoke the linker. This is calculated by the [`LANGUAGE`](../prop_sf/language#prop_sf:LANGUAGE "LANGUAGE") of source files in the target, and in the case of static libraries, the language of the dependent libraries. The choice CMake makes may be overridden with the [`LINKER_LANGUAGE`](../prop_tgt/linker_language#prop_tgt:LINKER_LANGUAGE "LINKER_LANGUAGE") target property.
Toolchain Features
------------------
CMake provides the [`try_compile()`](../command/try_compile#command:try_compile "try_compile") command and wrapper macros such as [`CheckCXXSourceCompiles`](../module/checkcxxsourcecompiles#module:CheckCXXSourceCompiles "CheckCXXSourceCompiles"), [`CheckCXXSymbolExists`](../module/checkcxxsymbolexists#module:CheckCXXSymbolExists "CheckCXXSymbolExists") and [`CheckIncludeFile`](../module/checkincludefile#module:CheckIncludeFile "CheckIncludeFile") to test capability and availability of various toolchain features. These APIs test the toolchain in some way and cache the result so that the test does not have to be performed again the next time CMake runs.
Some toolchain features have built-in handling in CMake, and do not require compile-tests. For example, [`POSITION_INDEPENDENT_CODE`](../prop_tgt/position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE") allows specifying that a target should be built as position-independent code, if the compiler supports that feature. The [`<LANG>_VISIBILITY_PRESET`](# "<LANG>_VISIBILITY_PRESET") and [`VISIBILITY_INLINES_HIDDEN`](../prop_tgt/visibility_inlines_hidden#prop_tgt:VISIBILITY_INLINES_HIDDEN "VISIBILITY_INLINES_HIDDEN") target properties add flags for hidden visibility, if supported by the compiler.
Cross Compiling
---------------
If [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") is invoked with the command line parameter `-DCMAKE_TOOLCHAIN_FILE=path/to/file`, the file will be loaded early to set values for the compilers. The [`CMAKE_CROSSCOMPILING`](../variable/cmake_crosscompiling#variable:CMAKE_CROSSCOMPILING "CMAKE_CROSSCOMPILING") variable is set to true when CMake is cross-compiling.
### Cross Compiling for Linux
A typical cross-compiling toolchain for Linux has content such as:
```
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)
set(CMAKE_SYSROOT /home/devel/rasp-pi-rootfs)
set(CMAKE_STAGING_PREFIX /home/devel/stage)
set(tools /home/devel/gcc-4.7-linaro-rpi-gnueabihf)
set(CMAKE_C_COMPILER ${tools}/bin/arm-linux-gnueabihf-gcc)
set(CMAKE_CXX_COMPILER ${tools}/bin/arm-linux-gnueabihf-g++)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
```
The [`CMAKE_SYSTEM_NAME`](../variable/cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME") is the CMake-identifier of the target platform to build for.
The [`CMAKE_SYSTEM_PROCESSOR`](../variable/cmake_system_processor#variable:CMAKE_SYSTEM_PROCESSOR "CMAKE_SYSTEM_PROCESSOR") is the CMake-identifier of the target architecture to build for.
The [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") is optional, and may be specified if a sysroot is available.
The [`CMAKE_STAGING_PREFIX`](../variable/cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX") is also optional. It may be used to specify a path on the host to install to. The [`CMAKE_INSTALL_PREFIX`](../variable/cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") is always the runtime installation location, even when cross-compiling.
The [`CMAKE_<LANG>_COMPILER`](# "CMAKE_<LANG>_COMPILER") variables may be set to full paths, or to names of compilers to search for in standard locations. For toolchains that do not support linking binaries without custom flags or scripts one may set the [`CMAKE_TRY_COMPILE_TARGET_TYPE`](../variable/cmake_try_compile_target_type#variable:CMAKE_TRY_COMPILE_TARGET_TYPE "CMAKE_TRY_COMPILE_TARGET_TYPE") variable to `STATIC_LIBRARY` to tell CMake not to try to link executables during its checks.
CMake `find_*` commands will look in the sysroot, and the [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") entries by default in all cases, as well as looking in the host system root prefix. Although this can be controlled on a case-by-case basis, when cross-compiling, it can be useful to exclude looking in either the host or the target for particular artifacts. Generally, includes, libraries and packages should be found in the target system prefixes, whereas executables which must be run as part of the build should be found only on the host and not on the target. This is the purpose of the `CMAKE_FIND_ROOT_PATH_MODE_*` variables.
### Cross Compiling for the Cray Linux Environment
Cross compiling for compute nodes in the Cray Linux Environment can be done without needing a separate toolchain file. Specifying `-DCMAKE_SYSTEM_NAME=CrayLinuxEnvironment` on the CMake command line will ensure that the appropriate build settings and search paths are configured. The platform will pull its configuration from the current environment variables and will configure a project to use the compiler wrappers from the Cray Programming Environment’s `PrgEnv-*` modules if present and loaded.
The default configuration of the Cray Programming Environment is to only support static libraries. This can be overridden and shared libraries enabled by setting the `CRAYPE_LINK_TYPE` environment variable to `dynamic`.
Running CMake without specifying [`CMAKE_SYSTEM_NAME`](../variable/cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME") will run the configure step in host mode assuming a standard Linux environment. If not overridden, the `PrgEnv-*` compiler wrappers will end up getting used, which if targeting the either the login node or compute node, is likely not the desired behavior. The exception to this would be if you are building directly on a NID instead of cross-compiling from a login node. If trying to build software for a login node, you will need to either first unload the currently loaded `PrgEnv-*` module or explicitly tell CMake to use the system compilers in `/usr/bin` instead of the Cray wrappers. If instead targeting a compute node is desired, just specify the [`CMAKE_SYSTEM_NAME`](../variable/cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME") as mentioned above.
### Cross Compiling using Clang
Some compilers such as Clang are inherently cross compilers. The [`CMAKE_<LANG>_COMPILER_TARGET`](# "CMAKE_<LANG>_COMPILER_TARGET") can be set to pass a value to those supported compilers when compiling:
```
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)
set(triple arm-linux-gnueabihf)
set(CMAKE_C_COMPILER clang)
set(CMAKE_C_COMPILER_TARGET ${triple})
set(CMAKE_CXX_COMPILER clang++)
set(CMAKE_CXX_COMPILER_TARGET ${triple})
```
Similarly, some compilers do not ship their own supplementary utilities such as linkers, but provide a way to specify the location of the external toolchain which will be used by the compiler driver. The [`CMAKE_<LANG>_COMPILER_EXTERNAL_TOOLCHAIN`](# "CMAKE_<LANG>_COMPILER_EXTERNAL_TOOLCHAIN") variable can be set in a toolchain file to pass the path to the compiler driver.
### Cross Compiling for QNX
As the Clang compiler the QNX QCC compile is inherently a cross compiler. And the [`CMAKE_<LANG>_COMPILER_TARGET`](# "CMAKE_<LANG>_COMPILER_TARGET") can be set to pass a value to those supported compilers when compiling:
```
set(CMAKE_SYSTEM_NAME QNX)
set(arch gcc_ntoarmv7le)
set(CMAKE_C_COMPILER qcc)
set(CMAKE_C_COMPILER_TARGET ${arch})
set(CMAKE_CXX_COMPILER QCC)
set(CMAKE_CXX_COMPILER_TARGET ${arch})
```
### Cross Compiling for Windows CE
Cross compiling for Windows CE requires the corresponding SDK being installed on your system. These SDKs are usually installed under `C:/Program Files (x86)/Windows CE Tools/SDKs`.
A toolchain file to configure a Visual Studio generator for Windows CE may look like this:
```
set(CMAKE_SYSTEM_NAME WindowsCE)
set(CMAKE_SYSTEM_VERSION 8.0)
set(CMAKE_SYSTEM_PROCESSOR arm)
set(CMAKE_GENERATOR_TOOLSET CE800) # Can be omitted for 8.0
set(CMAKE_GENERATOR_PLATFORM SDK_AM335X_SK_WEC2013_V310)
```
The [`CMAKE_GENERATOR_PLATFORM`](../variable/cmake_generator_platform#variable:CMAKE_GENERATOR_PLATFORM "CMAKE_GENERATOR_PLATFORM") tells the generator which SDK to use. Further [`CMAKE_SYSTEM_VERSION`](../variable/cmake_system_version#variable:CMAKE_SYSTEM_VERSION "CMAKE_SYSTEM_VERSION") tells the generator what version of Windows CE to use. Currently version 8.0 (Windows Embedded Compact 2013) is supported out of the box. Other versions may require one to set [`CMAKE_GENERATOR_TOOLSET`](../variable/cmake_generator_toolset#variable:CMAKE_GENERATOR_TOOLSET "CMAKE_GENERATOR_TOOLSET") to the correct value.
### Cross Compiling for Windows 10 Universal Applications
A toolchain file to configure a Visual Studio generator for a Windows 10 Universal Application may look like this:
```
set(CMAKE_SYSTEM_NAME WindowsStore)
set(CMAKE_SYSTEM_VERSION 10.0)
```
A Windows 10 Universal Application targets both Windows Store and Windows Phone. Specify the [`CMAKE_SYSTEM_VERSION`](../variable/cmake_system_version#variable:CMAKE_SYSTEM_VERSION "CMAKE_SYSTEM_VERSION") variable to be `10.0` to build with the latest available Windows 10 SDK. Specify a more specific version (e.g. `10.0.10240.0` for RTM) to build with the corresponding SDK.
### Cross Compiling for Windows Phone
A toolchain file to configure a Visual Studio generator for Windows Phone may look like this:
```
set(CMAKE_SYSTEM_NAME WindowsPhone)
set(CMAKE_SYSTEM_VERSION 8.1)
```
### Cross Compiling for Windows Store
A toolchain file to configure a Visual Studio generator for Windows Store may look like this:
```
set(CMAKE_SYSTEM_NAME WindowsStore)
set(CMAKE_SYSTEM_VERSION 8.1)
```
### Cross Compiling for Android
A toolchain file may configure cross-compiling for Android by setting the [`CMAKE_SYSTEM_NAME`](../variable/cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME") variable to `Android`. Further configuration is specific to the Android development environment to be used.
For [Visual Studio Generators](cmake-generators.7#visual-studio-generators), CMake expects [NVIDIA Nsight Tegra Visual Studio Edition](#cross-compiling-for-android-with-nvidia-nsight-tegra-visual-studio-edition) to be installed. See that section for further configuration details.
For [Makefile Generators](cmake-generators.7#makefile-generators) and the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator, CMake expects one of these environments:
* [NDK](#cross-compiling-for-android-with-the-ndk)
* [Standalone Toolchain](#cross-compiling-for-android-with-a-standalone-toolchain)
CMake uses the following steps to select one of the environments:
* If the [`CMAKE_ANDROID_NDK`](../variable/cmake_android_ndk#variable:CMAKE_ANDROID_NDK "CMAKE_ANDROID_NDK") variable is set, the NDK at the specified location will be used.
* Else, if the [`CMAKE_ANDROID_STANDALONE_TOOLCHAIN`](../variable/cmake_android_standalone_toolchain#variable:CMAKE_ANDROID_STANDALONE_TOOLCHAIN "CMAKE_ANDROID_STANDALONE_TOOLCHAIN") variable is set, the Standalone Toolchain at the specified location will be used.
* Else, if the [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") variable is set to a directory of the form `<ndk>/platforms/android-<api>/arch-<arch>`, the `<ndk>` part will be used as the value of [`CMAKE_ANDROID_NDK`](../variable/cmake_android_ndk#variable:CMAKE_ANDROID_NDK "CMAKE_ANDROID_NDK") and the NDK will be used.
* Else, if the [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") variable is set to a directory of the form `<standalone-toolchain>/sysroot`, the `<standalone-toolchain>` part will be used as the value of [`CMAKE_ANDROID_STANDALONE_TOOLCHAIN`](../variable/cmake_android_standalone_toolchain#variable:CMAKE_ANDROID_STANDALONE_TOOLCHAIN "CMAKE_ANDROID_STANDALONE_TOOLCHAIN") and the Standalone Toolchain will be used.
* Else, if a cmake variable `ANDROID_NDK` is set it will be used as the value of [`CMAKE_ANDROID_NDK`](../variable/cmake_android_ndk#variable:CMAKE_ANDROID_NDK "CMAKE_ANDROID_NDK"), and the NDK will be used.
* Else, if a cmake variable `ANDROID_STANDALONE_TOOLCHAIN` is set, it will be used as the value of [`CMAKE_ANDROID_STANDALONE_TOOLCHAIN`](../variable/cmake_android_standalone_toolchain#variable:CMAKE_ANDROID_STANDALONE_TOOLCHAIN "CMAKE_ANDROID_STANDALONE_TOOLCHAIN"), and the Standalone Toolchain will be used.
* Else, if an environment variable `ANDROID_NDK_ROOT` or `ANDROID_NDK` is set, it will be used as the value of [`CMAKE_ANDROID_NDK`](../variable/cmake_android_ndk#variable:CMAKE_ANDROID_NDK "CMAKE_ANDROID_NDK"), and the NDK will be used.
* Else, if an environment variable `ANDROID_STANDALONE_TOOLCHAIN` is set then it will be used as the value of [`CMAKE_ANDROID_STANDALONE_TOOLCHAIN`](../variable/cmake_android_standalone_toolchain#variable:CMAKE_ANDROID_STANDALONE_TOOLCHAIN "CMAKE_ANDROID_STANDALONE_TOOLCHAIN"), and the Standalone Toolchain will be used.
* Else, an error diagnostic will be issued that neither the NDK or Standalone Toolchain can be found.
#### Cross Compiling for Android with the NDK
A toolchain file may configure [Makefile Generators](cmake-generators.7#makefile-generators) or the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator to target Android for cross-compiling.
Configure use of an Android NDK with the following variables:
[`CMAKE_SYSTEM_NAME`](../variable/cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME")
Set to `Android`. Must be specified to enable cross compiling for Android.
[`CMAKE_SYSTEM_VERSION`](../variable/cmake_system_version#variable:CMAKE_SYSTEM_VERSION "CMAKE_SYSTEM_VERSION")
Set to the Android API level. If not specified, the value is determined as follows:
* If the [`CMAKE_ANDROID_API`](../variable/cmake_android_api#variable:CMAKE_ANDROID_API "CMAKE_ANDROID_API") variable is set, its value is used as the API level.
* If the [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") variable is set, the API level is detected from the NDK directory structure containing the sysroot.
* Otherwise, the latest API level available in the NDK is used.
[`CMAKE_ANDROID_ARCH_ABI`](../variable/cmake_android_arch_abi#variable:CMAKE_ANDROID_ARCH_ABI "CMAKE_ANDROID_ARCH_ABI")
Set to the Android ABI (architecture). If not specified, this variable will default to `armeabi`. The [`CMAKE_ANDROID_ARCH`](../variable/cmake_android_arch#variable:CMAKE_ANDROID_ARCH "CMAKE_ANDROID_ARCH") variable will be computed from `CMAKE_ANDROID_ARCH_ABI` automatically. Also see the [`CMAKE_ANDROID_ARM_MODE`](../variable/cmake_android_arm_mode#variable:CMAKE_ANDROID_ARM_MODE "CMAKE_ANDROID_ARM_MODE") and [`CMAKE_ANDROID_ARM_NEON`](../variable/cmake_android_arm_neon#variable:CMAKE_ANDROID_ARM_NEON "CMAKE_ANDROID_ARM_NEON") variables.
[`CMAKE_ANDROID_NDK`](../variable/cmake_android_ndk#variable:CMAKE_ANDROID_NDK "CMAKE_ANDROID_NDK")
Set to the absolute path to the Android NDK root directory. A `${CMAKE_ANDROID_NDK}/platforms` directory must exist. If not specified, a default for this variable will be chosen as specified [above](#cross-compiling-for-android).
[`CMAKE_ANDROID_NDK_DEPRECATED_HEADERS`](../variable/cmake_android_ndk_deprecated_headers#variable:CMAKE_ANDROID_NDK_DEPRECATED_HEADERS "CMAKE_ANDROID_NDK_DEPRECATED_HEADERS")
Set to a true value to use the deprecated per-api-level headers instead of the unified headers. If not specified, the default will be false unless using a NDK that does not provide unified headers.
[`CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION`](../variable/cmake_android_ndk_toolchain_version#variable:CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION "CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION")
Set to the version of the NDK toolchain to be selected as the compiler. If not specified, the default will be the latest available GCC toolchain.
[`CMAKE_ANDROID_STL_TYPE`](../variable/cmake_android_stl_type#variable:CMAKE_ANDROID_STL_TYPE "CMAKE_ANDROID_STL_TYPE")
Set to specify which C++ standard library to use. If not specified, a default will be selected as described in the variable documentation. The following variables will be computed and provided automatically:
[`CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX`](# "CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX")
The absolute path prefix to the binutils in the NDK toolchain.
[`CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX`](# "CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX")
The host platform suffix of the binutils in the NDK toolchain. For example, a toolchain file might contain:
```
set(CMAKE_SYSTEM_NAME Android)
set(CMAKE_SYSTEM_VERSION 21) # API level
set(CMAKE_ANDROID_ARCH_ABI arm64-v8a)
set(CMAKE_ANDROID_NDK /path/to/android-ndk)
set(CMAKE_ANDROID_STL_TYPE gnustl_static)
```
Alternatively one may specify the values without a toolchain file:
```
$ cmake ../src \
-DCMAKE_SYSTEM_NAME=Android \
-DCMAKE_SYSTEM_VERSION=21 \
-DCMAKE_ANDROID_ARCH_ABI=arm64-v8a \
-DCMAKE_ANDROID_NDK=/path/to/android-ndk \
-DCMAKE_ANDROID_STL_TYPE=gnustl_static
```
#### Cross Compiling for Android with a Standalone Toolchain
A toolchain file may configure [Makefile Generators](cmake-generators.7#makefile-generators) or the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator to target Android for cross-compiling using a standalone toolchain.
Configure use of an Android standalone toolchain with the following variables:
[`CMAKE_SYSTEM_NAME`](../variable/cmake_system_name#variable:CMAKE_SYSTEM_NAME "CMAKE_SYSTEM_NAME")
Set to `Android`. Must be specified to enable cross compiling for Android.
[`CMAKE_ANDROID_STANDALONE_TOOLCHAIN`](../variable/cmake_android_standalone_toolchain#variable:CMAKE_ANDROID_STANDALONE_TOOLCHAIN "CMAKE_ANDROID_STANDALONE_TOOLCHAIN")
Set to the absolute path to the standalone toolchain root directory. A `${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/sysroot` directory must exist. If not specified, a default for this variable will be chosen as specified [above](#cross-compiling-for-android).
[`CMAKE_ANDROID_ARM_MODE`](../variable/cmake_android_arm_mode#variable:CMAKE_ANDROID_ARM_MODE "CMAKE_ANDROID_ARM_MODE")
When the standalone toolchain targets ARM, optionally set this to `ON` to target 32-bit ARM instead of 16-bit Thumb. See variable documentation for details.
[`CMAKE_ANDROID_ARM_NEON`](../variable/cmake_android_arm_neon#variable:CMAKE_ANDROID_ARM_NEON "CMAKE_ANDROID_ARM_NEON")
When the standalone toolchain targets ARM v7, optionally set thisto `ON` to target ARM NEON devices. See variable documentation for details. The following variables will be computed and provided automatically:
[`CMAKE_SYSTEM_VERSION`](../variable/cmake_system_version#variable:CMAKE_SYSTEM_VERSION "CMAKE_SYSTEM_VERSION")
The Android API level detected from the standalone toolchain.
[`CMAKE_ANDROID_ARCH_ABI`](../variable/cmake_android_arch_abi#variable:CMAKE_ANDROID_ARCH_ABI "CMAKE_ANDROID_ARCH_ABI")
The Android ABI detected from the standalone toolchain.
[`CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX`](# "CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX")
The absolute path prefix to the binutils in the standalone toolchain.
[`CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX`](# "CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX")
The host platform suffix of the binutils in the standalone toolchain. For example, a toolchain file might contain:
```
set(CMAKE_SYSTEM_NAME Android)
set(CMAKE_ANDROID_STANDALONE_TOOLCHAIN /path/to/android-toolchain)
```
Alternatively one may specify the values without a toolchain file:
```
$ cmake ../src \
-DCMAKE_SYSTEM_NAME=Android \
-DCMAKE_ANDROID_STANDALONE_TOOLCHAIN=/path/to/android-toolchain
```
#### Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio Edition
A toolchain file to configure one of the [Visual Studio Generators](cmake-generators.7#visual-studio-generators) to build using NVIDIA Nsight Tegra targeting Android may look like this:
```
set(CMAKE_SYSTEM_NAME Android)
```
The [`CMAKE_GENERATOR_TOOLSET`](../variable/cmake_generator_toolset#variable:CMAKE_GENERATOR_TOOLSET "CMAKE_GENERATOR_TOOLSET") may be set to select the Nsight Tegra “Toolchain Version” value.
See also target properties:
* [`ANDROID_ANT_ADDITIONAL_OPTIONS`](../prop_tgt/android_ant_additional_options#prop_tgt:ANDROID_ANT_ADDITIONAL_OPTIONS "ANDROID_ANT_ADDITIONAL_OPTIONS")
* [`ANDROID_API_MIN`](../prop_tgt/android_api_min#prop_tgt:ANDROID_API_MIN "ANDROID_API_MIN")
* [`ANDROID_API`](../prop_tgt/android_api#prop_tgt:ANDROID_API "ANDROID_API")
* [`ANDROID_ARCH`](../prop_tgt/android_arch#prop_tgt:ANDROID_ARCH "ANDROID_ARCH")
* [`ANDROID_ASSETS_DIRECTORIES`](../prop_tgt/android_assets_directories#prop_tgt:ANDROID_ASSETS_DIRECTORIES "ANDROID_ASSETS_DIRECTORIES")
* [`ANDROID_GUI`](../prop_tgt/android_gui#prop_tgt:ANDROID_GUI "ANDROID_GUI")
* [`ANDROID_JAR_DEPENDENCIES`](../prop_tgt/android_jar_dependencies#prop_tgt:ANDROID_JAR_DEPENDENCIES "ANDROID_JAR_DEPENDENCIES")
* [`ANDROID_JAR_DIRECTORIES`](../prop_tgt/android_jar_directories#prop_tgt:ANDROID_JAR_DIRECTORIES "ANDROID_JAR_DIRECTORIES")
* [`ANDROID_JAVA_SOURCE_DIR`](../prop_tgt/android_java_source_dir#prop_tgt:ANDROID_JAVA_SOURCE_DIR "ANDROID_JAVA_SOURCE_DIR")
* [`ANDROID_NATIVE_LIB_DEPENDENCIES`](../prop_tgt/android_native_lib_dependencies#prop_tgt:ANDROID_NATIVE_LIB_DEPENDENCIES "ANDROID_NATIVE_LIB_DEPENDENCIES")
* [`ANDROID_NATIVE_LIB_DIRECTORIES`](../prop_tgt/android_native_lib_directories#prop_tgt:ANDROID_NATIVE_LIB_DIRECTORIES "ANDROID_NATIVE_LIB_DIRECTORIES")
* [`ANDROID_PROCESS_MAX`](../prop_tgt/android_process_max#prop_tgt:ANDROID_PROCESS_MAX "ANDROID_PROCESS_MAX")
* [`ANDROID_PROGUARD_CONFIG_PATH`](../prop_tgt/android_proguard_config_path#prop_tgt:ANDROID_PROGUARD_CONFIG_PATH "ANDROID_PROGUARD_CONFIG_PATH")
* [`ANDROID_PROGUARD`](../prop_tgt/android_proguard#prop_tgt:ANDROID_PROGUARD "ANDROID_PROGUARD")
* [`ANDROID_SECURE_PROPS_PATH`](../prop_tgt/android_secure_props_path#prop_tgt:ANDROID_SECURE_PROPS_PATH "ANDROID_SECURE_PROPS_PATH")
* [`ANDROID_SKIP_ANT_STEP`](../prop_tgt/android_skip_ant_step#prop_tgt:ANDROID_SKIP_ANT_STEP "ANDROID_SKIP_ANT_STEP")
* [`ANDROID_STL_TYPE`](../prop_tgt/android_stl_type#prop_tgt:ANDROID_STL_TYPE "ANDROID_STL_TYPE")
| programming_docs |
cmake cmake-policies(7) cmake-policies(7)
=================
* [Introduction](#introduction)
* [Policies Introduced by CMake 3.9](#policies-introduced-by-cmake-3-9)
* [Policies Introduced by CMake 3.8](#policies-introduced-by-cmake-3-8)
* [Policies Introduced by CMake 3.7](#policies-introduced-by-cmake-3-7)
* [Policies Introduced by CMake 3.4](#policies-introduced-by-cmake-3-4)
* [Policies Introduced by CMake 3.3](#policies-introduced-by-cmake-3-3)
* [Policies Introduced by CMake 3.2](#policies-introduced-by-cmake-3-2)
* [Policies Introduced by CMake 3.1](#policies-introduced-by-cmake-3-1)
* [Policies Introduced by CMake 3.0](#policies-introduced-by-cmake-3-0)
* [Policies Introduced by CMake 2.8](#policies-introduced-by-cmake-2-8)
* [Policies Introduced by CMake 2.6](#policies-introduced-by-cmake-2-6)
Introduction
------------
Policies in CMake are used to preserve backward compatible behavior across multiple releases. When a new policy is introduced, newer CMake versions will begin to warn about the backward compatible behavior. It is possible to disable the warning by explicitly requesting the OLD, or backward compatible behavior using the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command. It is also possible to request `NEW`, or non-backward compatible behavior for a policy, also avoiding the warning. Each policy can also be set to either `NEW` or `OLD` behavior explicitly on the command line with the [`CMAKE_POLICY_DEFAULT_CMP<NNNN>`](# "CMAKE_POLICY_DEFAULT_CMP<NNNN>") variable.
A policy is a deprecation mechanism and not a reliable feature toggle. A policy should almost never be set to `OLD`, except to silence warnings in an otherwise frozen or stable codebase, or temporarily as part of a larger migration path. The `OLD` behavior of each policy is undesirable and will be replaced with an error condition in a future release.
The [`cmake_minimum_required()`](../command/cmake_minimum_required#command:cmake_minimum_required "cmake_minimum_required") command does more than report an error if a too-old version of CMake is used to build a project. It also sets all policies introduced in that CMake version or earlier to `NEW` behavior. To manage policies without increasing the minimum required CMake version, the [`if(POLICY)`](../command/if#command:if "if") command may be used:
```
if(POLICY CMP0990)
cmake_policy(SET CMP0990 NEW)
endif()
```
This has the effect of using the `NEW` behavior with newer CMake releases which users may be using and not issuing a compatibility warning.
The setting of a policy is confined in some cases to not propagate to the parent scope. For example, if the files read by the [`include()`](../command/include#command:include "include") command or the [`find_package()`](../command/find_package#command:find_package "find_package") command contain a use of [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy"), that policy setting will not affect the caller by default. Both commands accept an optional `NO_POLICY_SCOPE` keyword to control this behavior.
The [`CMAKE_MINIMUM_REQUIRED_VERSION`](../variable/cmake_minimum_required_version#variable:CMAKE_MINIMUM_REQUIRED_VERSION "CMAKE_MINIMUM_REQUIRED_VERSION") variable may also be used to determine whether to report an error on use of deprecated macros or functions.
Policies Introduced by CMake 3.9
--------------------------------
* [CMP0069: INTERPROCEDURAL\_OPTIMIZATION is enforced when enabled.](../policy/cmp0069)
* [CMP0068: RPATH settings on macOS do not affect install\_name.](../policy/cmp0068)
Policies Introduced by CMake 3.8
--------------------------------
* [CMP0067: Honor language standard in try\_compile() source-file signature.](../policy/cmp0067)
Policies Introduced by CMake 3.7
--------------------------------
* [CMP0066: Honor per-config flags in try\_compile() source-file signature.](../policy/cmp0066)
Policies Introduced by CMake 3.4
--------------------------------
* [CMP0065: Do not add flags to export symbols from executables without the ENABLE\_EXPORTS target property.](../policy/cmp0065)
* [CMP0064: Support new TEST if() operator.](../policy/cmp0064)
Policies Introduced by CMake 3.3
--------------------------------
* [CMP0063: Honor visibility properties for all target types.](../policy/cmp0063)
* [CMP0062: Disallow install() of export() result.](../policy/cmp0062)
* [CMP0061: CTest does not by default tell make to ignore errors (-i).](../policy/cmp0061)
* [CMP0060: Link libraries by full path even in implicit directories.](../policy/cmp0060)
* [CMP0059: Do not treat DEFINITIONS as a built-in directory property.](../policy/cmp0059)
* [CMP0058: Ninja requires custom command byproducts to be explicit.](../policy/cmp0058)
* [CMP0057: Support new IN\_LIST if() operator.](../policy/cmp0057)
Policies Introduced by CMake 3.2
--------------------------------
* [CMP0056: Honor link flags in try\_compile() source-file signature.](../policy/cmp0056)
* [CMP0055: Strict checking for break() command.](../policy/cmp0055)
Policies Introduced by CMake 3.1
--------------------------------
* [CMP0054: Only interpret if() arguments as variables or keywords when unquoted.](../policy/cmp0054)
* [CMP0053: Simplify variable reference and escape sequence evaluation.](../policy/cmp0053)
* [CMP0052: Reject source and build dirs in installed INTERFACE\_INCLUDE\_DIRECTORIES.](../policy/cmp0052)
* [CMP0051: List TARGET\_OBJECTS in SOURCES target property.](../policy/cmp0051)
Policies Introduced by CMake 3.0
--------------------------------
* [CMP0050: Disallow add\_custom\_command SOURCE signatures.](../policy/cmp0050)
* [CMP0049: Do not expand variables in target source entries.](../policy/cmp0049)
* [CMP0048: project() command manages VERSION variables.](../policy/cmp0048)
* [CMP0047: Use QCC compiler id for the qcc drivers on QNX.](../policy/cmp0047)
* [CMP0046: Error on non-existent dependency in add\_dependencies.](../policy/cmp0046)
* [CMP0045: Error on non-existent target in get\_target\_property.](../policy/cmp0045)
* [CMP0044: Case sensitive Lang\_COMPILER\_ID generator expressions.](../policy/cmp0044)
* [CMP0043: Ignore COMPILE\_DEFINITIONS\_Config properties.](../policy/cmp0043)
* [CMP0042: MACOSX\_RPATH is enabled by default.](../policy/cmp0042)
* [CMP0041: Error on relative include with generator expression.](../policy/cmp0041)
* [CMP0040: The target in the TARGET signature of add\_custom\_command() must exist.](../policy/cmp0040)
* [CMP0039: Utility targets may not have link dependencies.](../policy/cmp0039)
* [CMP0038: Targets may not link directly to themselves.](../policy/cmp0038)
* [CMP0037: Target names should not be reserved and should match a validity pattern.](../policy/cmp0037)
* [CMP0036: The build\_name command should not be called.](../policy/cmp0036)
* [CMP0035: The variable\_requires command should not be called.](../policy/cmp0035)
* [CMP0034: The utility\_source command should not be called.](../policy/cmp0034)
* [CMP0033: The export\_library\_dependencies command should not be called.](../policy/cmp0033)
* [CMP0032: The output\_required\_files command should not be called.](../policy/cmp0032)
* [CMP0031: The load\_command command should not be called.](../policy/cmp0031)
* [CMP0030: The use\_mangled\_mesa command should not be called.](../policy/cmp0030)
* [CMP0029: The subdir\_depends command should not be called.](../policy/cmp0029)
* [CMP0028: Double colon in target name means ALIAS or IMPORTED target.](../policy/cmp0028)
* [CMP0027: Conditionally linked imported targets with missing include directories.](../policy/cmp0027)
* [CMP0026: Disallow use of the LOCATION target property.](../policy/cmp0026)
* [CMP0025: Compiler id for Apple Clang is now AppleClang.](../policy/cmp0025)
* [CMP0024: Disallow include export result.](../policy/cmp0024)
Policies Introduced by CMake 2.8
--------------------------------
* [CMP0023: Plain and keyword target\_link\_libraries signatures cannot be mixed.](../policy/cmp0023)
* [CMP0022: INTERFACE\_LINK\_LIBRARIES defines the link interface.](../policy/cmp0022)
* [CMP0021: Fatal error on relative paths in INCLUDE\_DIRECTORIES target property.](../policy/cmp0021)
* [CMP0020: Automatically link Qt executables to qtmain target on Windows.](../policy/cmp0020)
* [CMP0019: Do not re-expand variables in include and link information.](../policy/cmp0019)
* [CMP0018: Ignore CMAKE\_SHARED\_LIBRARY\_Lang\_FLAGS variable.](../policy/cmp0018)
* [CMP0017: Prefer files from the CMake module directory when including from there.](../policy/cmp0017)
* [CMP0016: target\_link\_libraries() reports error if its only argument is not a target.](../policy/cmp0016)
* [CMP0015: link\_directories() treats paths relative to the source dir.](../policy/cmp0015)
* [CMP0014: Input directories must have CMakeLists.txt.](../policy/cmp0014)
* [CMP0013: Duplicate binary directories are not allowed.](../policy/cmp0013)
* [CMP0012: if() recognizes numbers and boolean constants.](../policy/cmp0012)
Policies Introduced by CMake 2.6
--------------------------------
* [CMP0011: Included scripts do automatic cmake\_policy PUSH and POP.](../policy/cmp0011)
* [CMP0010: Bad variable reference syntax is an error.](../policy/cmp0010)
* [CMP0009: FILE GLOB\_RECURSE calls should not follow symlinks by default.](../policy/cmp0009)
* [CMP0008: Libraries linked by full-path must have a valid library file name.](../policy/cmp0008)
* [CMP0007: list command no longer ignores empty elements.](../policy/cmp0007)
* [CMP0006: Installing MACOSX\_BUNDLE targets requires a BUNDLE DESTINATION.](../policy/cmp0006)
* [CMP0005: Preprocessor definition values are now escaped automatically.](../policy/cmp0005)
* [CMP0004: Libraries linked may not have leading or trailing whitespace.](../policy/cmp0004)
* [CMP0003: Libraries linked via full path no longer produce linker search paths.](../policy/cmp0003)
* [CMP0002: Logical target names must be globally unique.](../policy/cmp0002)
* [CMP0001: CMAKE\_BACKWARDS\_COMPATIBILITY should no longer be used.](../policy/cmp0001)
* [CMP0000: A minimum required CMake version must be specified.](../policy/cmp0000)
cmake cmake-qt(7) cmake-qt(7)
===========
* [Introduction](#introduction)
* [Qt Build Tools](#qt-build-tools)
+ [AUTOMOC](#automoc)
+ [AUTOUIC](#autouic)
+ [AUTORCC](#autorcc)
* [qtmain.lib on Windows](#qtmain-lib-on-windows)
Introduction
------------
CMake can find and use Qt 4 and Qt 5 libraries. The Qt 4 libraries are found by the [`FindQt4`](../module/findqt4#module:FindQt4 "FindQt4") find-module shipped with CMake, whereas the Qt 5 libraries are found using “Config-file Packages” shipped with Qt 5. See [`cmake-packages(7)`](cmake-packages.7#manual:cmake-packages(7) "cmake-packages(7)") for more information about CMake packages, and see [the Qt cmake manual](http://qt-project.org/doc/qt-5/cmake-manual.html) for your Qt version.
Qt 4 and Qt 5 may be used together in the same [`CMake buildsystem`](cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)"):
```
cmake_minimum_required(VERSION 3.8.0 FATAL_ERROR)
project(Qt4And5)
set(CMAKE_AUTOMOC ON)
find_package(Qt5 COMPONENTS Widgets DBus REQUIRED)
add_executable(publisher publisher.cpp)
target_link_libraries(publisher Qt5::Widgets Qt5::DBus)
find_package(Qt4 REQUIRED)
add_executable(subscriber subscriber.cpp)
target_link_libraries(subscriber Qt4::QtGui Qt4::QtDBus)
```
A CMake target may not link to both Qt 4 and Qt 5. A diagnostic is issued if this is attempted or results from transitive target dependency evaluation.
Qt Build Tools
--------------
Qt relies on some bundled tools for code generation, such as `moc` for meta-object code generation, `uic` for widget layout and population, and `rcc` for virtual filesystem content generation. These tools may be automatically invoked by [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") if the appropriate conditions are met. The automatic tool invocation may be used with both Qt 4 and Qt 5.
The tools are executed as part of a synthesized custom target generated by CMake. Target dependencies may be added to that custom target by adding them to the [`AUTOGEN_TARGET_DEPENDS`](../prop_tgt/autogen_target_depends#prop_tgt:AUTOGEN_TARGET_DEPENDS "AUTOGEN_TARGET_DEPENDS") target property.
### AUTOMOC
The [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") target property controls whether [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") inspects the C++ files in the target to determine if they require `moc` to be run, and to create rules to execute `moc` at the appropriate time.
If a `Q_OBJECT` or `Q_GADGET` macro is found in a header file, `moc` will be run on the file. The result will be put into a file named according to `moc_<basename>.cpp`. If the macro is found in a C++ implementation file, the moc output will be put into a file named according to `<basename>.moc`, following the Qt conventions. The `<basename>.moc` must be included by the user in the C++ implementation file with a preprocessor `#include`.
Included `moc_*.cpp` and `*.moc` files will be generated in the `<AUTOGEN_BUILD_DIR>/include` directory which is automatically added to the target’s [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES").
* This differs from CMake 3.7 and below; see their documentation for details.
* See [`AUTOGEN_BUILD_DIR`](../prop_tgt/autogen_build_dir#prop_tgt:AUTOGEN_BUILD_DIR "AUTOGEN_BUILD_DIR").
Not included `moc_<basename>.cpp` files will be generated in custom folders to avoid name collisions and included in a separate `<AUTOGEN_BUILD_DIR>/mocs_compilation.cpp` file which is compiled into the target.
* See [`AUTOGEN_BUILD_DIR`](../prop_tgt/autogen_build_dir#prop_tgt:AUTOGEN_BUILD_DIR "AUTOGEN_BUILD_DIR").
The `moc` command line will consume the [`COMPILE_DEFINITIONS`](../prop_tgt/compile_definitions#prop_tgt:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") and [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES") target properties from the target it is being invoked for, and for the appropriate build configuration.
The [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") target property may be pre-set for all following targets by setting the [`CMAKE_AUTOMOC`](../variable/cmake_automoc#variable:CMAKE_AUTOMOC "CMAKE_AUTOMOC") variable. The [`AUTOMOC_MOC_OPTIONS`](../prop_tgt/automoc_moc_options#prop_tgt:AUTOMOC_MOC_OPTIONS "AUTOMOC_MOC_OPTIONS") target property may be populated to set options to pass to `moc`. The [`CMAKE_AUTOMOC_MOC_OPTIONS`](../variable/cmake_automoc_moc_options#variable:CMAKE_AUTOMOC_MOC_OPTIONS "CMAKE_AUTOMOC_MOC_OPTIONS") variable may be populated to pre-set the options for all following targets.
Additional `moc` dependency file names can be extracted from source code by using [`AUTOMOC_DEPEND_FILTERS`](../prop_tgt/automoc_depend_filters#prop_tgt:AUTOMOC_DEPEND_FILTERS "AUTOMOC_DEPEND_FILTERS").
Source C++ files can be excluded from [`AUTOMOC`](../prop_tgt/automoc#prop_tgt:AUTOMOC "AUTOMOC") processing by enabling [`SKIP_AUTOMOC`](../prop_sf/skip_automoc#prop_sf:SKIP_AUTOMOC "SKIP_AUTOMOC") or the broader [`SKIP_AUTOGEN`](../prop_sf/skip_autogen#prop_sf:SKIP_AUTOGEN "SKIP_AUTOGEN").
### AUTOUIC
The [`AUTOUIC`](../prop_tgt/autouic#prop_tgt:AUTOUIC "AUTOUIC") target property controls whether [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") inspects the C++ files in the target to determine if they require `uic` to be run, and to create rules to execute `uic` at the appropriate time.
If a preprocessor `#include` directive is found which matches `<path>ui_<basename>.h`, and a `<basename>.ui` file exists, then `uic` will be executed to generate the appropriate file. The `<basename>.ui` file is searched for in the following places
1. `<source_dir>/<basename>.ui`
2. `<source_dir>/<path><basename>.ui`
3. `<AUTOUIC_SEARCH_PATHS>/<basename>.ui`
4. `<AUTOUIC_SEARCH_PATHS>/<path><basename>.ui`
where `<source_dir>` is the directory of the C++ file and [`AUTOUIC_SEARCH_PATHS`](../prop_tgt/autouic_search_paths#prop_tgt:AUTOUIC_SEARCH_PATHS "AUTOUIC_SEARCH_PATHS") is a list of additional search paths.
The generated generated `ui_*.h` files are placed in the `<AUTOGEN_BUILD_DIR>/include` directory which is automatically added to the target’s [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES").
* This differs from CMake 3.7 and below; see their documentation for details.
* See [`AUTOGEN_BUILD_DIR`](../prop_tgt/autogen_build_dir#prop_tgt:AUTOGEN_BUILD_DIR "AUTOGEN_BUILD_DIR").
The [`AUTOUIC`](../prop_tgt/autouic#prop_tgt:AUTOUIC "AUTOUIC") target property may be pre-set for all following targets by setting the [`CMAKE_AUTOUIC`](../variable/cmake_autouic#variable:CMAKE_AUTOUIC "CMAKE_AUTOUIC") variable. The [`AUTOUIC_OPTIONS`](../prop_tgt/autouic_options#prop_tgt:AUTOUIC_OPTIONS "AUTOUIC_OPTIONS") target property may be populated to set options to pass to `uic`. The [`CMAKE_AUTOUIC_OPTIONS`](../variable/cmake_autouic_options#variable:CMAKE_AUTOUIC_OPTIONS "CMAKE_AUTOUIC_OPTIONS") variable may be populated to pre-set the options for all following targets. The [`AUTOUIC_OPTIONS`](../prop_sf/autouic_options#prop_sf:AUTOUIC_OPTIONS "AUTOUIC_OPTIONS") source file property may be set on the `<basename>.ui` file to set particular options for the file. This overrides options from the [`AUTOUIC_OPTIONS`](../prop_tgt/autouic_options#prop_tgt:AUTOUIC_OPTIONS "AUTOUIC_OPTIONS") target property.
A target may populate the [`INTERFACE_AUTOUIC_OPTIONS`](../prop_tgt/interface_autouic_options#prop_tgt:INTERFACE_AUTOUIC_OPTIONS "INTERFACE_AUTOUIC_OPTIONS") target property with options that should be used when invoking `uic`. This must be consistent with the [`AUTOUIC_OPTIONS`](../prop_tgt/autouic_options#prop_tgt:AUTOUIC_OPTIONS "AUTOUIC_OPTIONS") target property content of the depender target. The [`CMAKE_DEBUG_TARGET_PROPERTIES`](../variable/cmake_debug_target_properties#variable:CMAKE_DEBUG_TARGET_PROPERTIES "CMAKE_DEBUG_TARGET_PROPERTIES") variable may be used to track the origin target of such [`INTERFACE_AUTOUIC_OPTIONS`](../prop_tgt/interface_autouic_options#prop_tgt:INTERFACE_AUTOUIC_OPTIONS "INTERFACE_AUTOUIC_OPTIONS"). This means that a library which provides an alternative translation system for Qt may specify options which should be used when running `uic`:
```
add_library(KI18n klocalizedstring.cpp)
target_link_libraries(KI18n Qt5::Core)
# KI18n uses the tr2i18n() function instead of tr(). That function is
# declared in the klocalizedstring.h header.
set(autouic_options
-tr tr2i18n
-include klocalizedstring.h
)
set_property(TARGET KI18n APPEND PROPERTY
INTERFACE_AUTOUIC_OPTIONS ${autouic_options}
)
```
A consuming project linking to the target exported from upstream automatically uses appropriate options when `uic` is run by [`AUTOUIC`](../prop_tgt/autouic#prop_tgt:AUTOUIC "AUTOUIC"), as a result of linking with the [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target:
```
set(CMAKE_AUTOUIC ON)
# Uses a libwidget.ui file:
add_library(LibWidget libwidget.cpp)
target_link_libraries(LibWidget
KF5::KI18n
Qt5::Widgets
)
```
Source files can be excluded from [`AUTOUIC`](../prop_tgt/autouic#prop_tgt:AUTOUIC "AUTOUIC") processing by enabling [`SKIP_AUTOUIC`](../prop_sf/skip_autouic#prop_sf:SKIP_AUTOUIC "SKIP_AUTOUIC") or the broader [`SKIP_AUTOGEN`](../prop_sf/skip_autogen#prop_sf:SKIP_AUTOGEN "SKIP_AUTOGEN").
### AUTORCC
The [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC") target property controls whether [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") creates rules to execute `rcc` at the appropriate time on source files which have the suffix `.qrc`.
```
add_executable(myexe main.cpp resource_file.qrc)
```
The [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC") target property may be pre-set for all following targets by setting the [`CMAKE_AUTORCC`](../variable/cmake_autorcc#variable:CMAKE_AUTORCC "CMAKE_AUTORCC") variable. The [`AUTORCC_OPTIONS`](../prop_tgt/autorcc_options#prop_tgt:AUTORCC_OPTIONS "AUTORCC_OPTIONS") target property may be populated to set options to pass to `rcc`. The [`CMAKE_AUTORCC_OPTIONS`](../variable/cmake_autorcc_options#variable:CMAKE_AUTORCC_OPTIONS "CMAKE_AUTORCC_OPTIONS") variable may be populated to pre-set the options for all following targets. The [`AUTORCC_OPTIONS`](../prop_sf/autorcc_options#prop_sf:AUTORCC_OPTIONS "AUTORCC_OPTIONS") source file property may be set on the `<name>.qrc` file to set particular options for the file. This overrides options from the [`AUTORCC_OPTIONS`](../prop_tgt/autorcc_options#prop_tgt:AUTORCC_OPTIONS "AUTORCC_OPTIONS") target property.
Source files can be excluded from [`AUTORCC`](../prop_tgt/autorcc#prop_tgt:AUTORCC "AUTORCC") processing by enabling [`SKIP_AUTORCC`](../prop_sf/skip_autorcc#prop_sf:SKIP_AUTORCC "SKIP_AUTORCC") or the broader [`SKIP_AUTOGEN`](../prop_sf/skip_autogen#prop_sf:SKIP_AUTOGEN "SKIP_AUTOGEN").
qtmain.lib on Windows
---------------------
The Qt 4 and 5 [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets for the QtGui libraries specify that the qtmain.lib static library shipped with Qt will be linked by all dependent executables which have the [`WIN32_EXECUTABLE`](../prop_tgt/win32_executable#prop_tgt:WIN32_EXECUTABLE "WIN32_EXECUTABLE") enabled.
To disable this behavior, enable the `Qt5_NO_LINK_QTMAIN` target property for Qt 5 based targets or `QT4_NO_LINK_QTMAIN` target property for Qt 4 based targets.
```
add_executable(myexe WIN32 main.cpp)
target_link_libraries(myexe Qt4::QtGui)
add_executable(myexe_no_qtmain WIN32 main_no_qtmain.cpp)
set_property(TARGET main_no_qtmain PROPERTY QT4_NO_LINK_QTMAIN ON)
target_link_libraries(main_no_qtmain Qt4::QtGui)
```
| programming_docs |
cmake cmake-language(7) cmake-language(7)
=================
* [Organization](#organization)
+ [Directories](#directories)
+ [Scripts](#scripts)
+ [Modules](#modules)
* [Syntax](#syntax)
+ [Encoding](#encoding)
+ [Source Files](#source-files)
+ [Command Invocations](#command-invocations)
+ [Command Arguments](#command-arguments)
- [Bracket Argument](#bracket-argument)
- [Quoted Argument](#quoted-argument)
- [Unquoted Argument](#unquoted-argument)
+ [Escape Sequences](#escape-sequences)
+ [Variable References](#variable-references)
+ [Comments](#comments)
- [Bracket Comment](#bracket-comment)
- [Line Comment](#line-comment)
* [Control Structures](#control-structures)
+ [Conditional Blocks](#conditional-blocks)
+ [Loops](#loops)
+ [Command Definitions](#command-definitions)
* [Variables](#variables)
* [Lists](#lists)
Organization
------------
CMake input files are written in the “CMake Language” in source files named `CMakeLists.txt` or ending in a `.cmake` file name extension.
CMake Language source files in a project are organized into:
* [Directories](#directories) (`CMakeLists.txt`),
* [Scripts](#scripts) (`<script>.cmake`), and
* [Modules](#modules) (`<module>.cmake`).
### Directories
When CMake processes a project source tree, the entry point is a source file called `CMakeLists.txt` in the top-level source directory. This file may contain the entire build specification or use the [`add_subdirectory()`](../command/add_subdirectory#command:add_subdirectory "add_subdirectory") command to add subdirectories to the build. Each subdirectory added by the command must also contain a `CMakeLists.txt` file as the entry point to that directory. For each source directory whose `CMakeLists.txt` file is processed CMake generates a corresponding directory in the build tree to act as the default working and output directory.
### Scripts
An individual `<script>.cmake` source file may be processed in *script mode* by using the [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") command-line tool with the `-P` option. Script mode simply runs the commands in the given CMake Language source file and does not generate a build system. It does not allow CMake commands that define build targets or actions.
### Modules
CMake Language code in either [Directories](#directories) or [Scripts](#scripts) may use the [`include()`](../command/include#command:include "include") command to load a `<module>.cmake` source file in the scope of the including context. See the [`cmake-modules(7)`](cmake-modules.7#manual:cmake-modules(7) "cmake-modules(7)") manual page for documentation of modules included with the CMake distribution. Project source trees may also provide their own modules and specify their location(s) in the [`CMAKE_MODULE_PATH`](../variable/cmake_module_path#variable:CMAKE_MODULE_PATH "CMAKE_MODULE_PATH") variable.
Syntax
------
### Encoding
A CMake Language source file may be written in 7-bit ASCII text for maximum portability across all supported platforms. Newlines may be encoded as either `\n` or `\r\n` but will be converted to `\n` as input files are read.
Note that the implementation is 8-bit clean so source files may be encoded as UTF-8 on platforms with system APIs supporting this encoding. In addition, CMake 3.2 and above support source files encoded in UTF-8 on Windows (using UTF-16 to call system APIs). Furthermore, CMake 3.0 and above allow a leading UTF-8 [Byte-Order Mark](http://en.wikipedia.org/wiki/Byte_order_mark) in source files.
### Source Files
A CMake Language source file consists of zero or more [Command Invocations](#command-invocations) separated by newlines and optionally spaces and [Comments](#comments):
```
**file** ::= [file\_element](#grammar-token-file_element)*
**file\_element** ::= [command\_invocation](#grammar-token-command_invocation) [line\_ending](#grammar-token-line_ending) |
([bracket\_comment](#grammar-token-bracket_comment)|[space](#grammar-token-space))* [line\_ending](#grammar-token-line_ending)
**line\_ending** ::= [line\_comment](#grammar-token-line_comment)? [newline](#grammar-token-newline)
**space** ::= <match '[ \t]+'>
**newline** ::= <match '\n'>
```
Note that any source file line not inside [Command Arguments](#command-arguments) or a [Bracket Comment](#bracket-comment) can end in a [Line Comment](#line-comment).
### Command Invocations
A *command invocation* is a name followed by paren-enclosed arguments separated by whitespace:
```
**command\_invocation** ::= [space](#grammar-token-space)* [identifier](#grammar-token-identifier) [space](#grammar-token-space)* '(' [arguments](#grammar-token-arguments) ')'
**identifier** ::= <match '[A-Za-z_][A-Za-z0-9_]*'>
**arguments** ::= [argument](#grammar-token-argument)? [separated\_arguments](#grammar-token-separated_arguments)*
**separated\_arguments** ::= [separation](#grammar-token-separation)+ [argument](#grammar-token-argument)? |
[separation](#grammar-token-separation)* '(' [arguments](#grammar-token-arguments) ')'
**separation** ::= [space](#grammar-token-space) | [line\_ending](#grammar-token-line_ending)
```
For example:
```
add_executable(hello world.c)
```
Command names are case-insensitive. Nested unquoted parentheses in the arguments must balance. Each `(` or `)` is given to the command invocation as a literal [Unquoted Argument](#unquoted-argument). This may be used in calls to the [`if()`](../command/if#command:if "if") command to enclose conditions. For example:
```
if(FALSE AND (FALSE OR TRUE)) # evaluates to FALSE
```
Note
CMake versions prior to 3.0 require command name identifiers to be at least 2 characters.
CMake versions prior to 2.8.12 silently accept an [Unquoted Argument](#unquoted-argument) or a [Quoted Argument](#quoted-argument) immediately following a [Quoted Argument](#quoted-argument) and not separated by any whitespace. For compatibility, CMake 2.8.12 and higher accept such code but produce a warning.
### Command Arguments
There are three types of arguments within [Command Invocations](#command-invocations):
```
**argument** ::= [bracket\_argument](#grammar-token-bracket_argument) | [quoted\_argument](#grammar-token-quoted_argument) | [unquoted\_argument](#grammar-token-unquoted_argument)
```
#### Bracket Argument
A *bracket argument*, inspired by [Lua](http://www.lua.org/) long bracket syntax, encloses content between opening and closing “brackets” of the same length:
```
**bracket\_argument** ::= [bracket\_open](#grammar-token-bracket_open) [bracket\_content](#grammar-token-bracket_content) [bracket\_close](#grammar-token-bracket_close)
**bracket\_open** ::= '[' '='{len} '['
**bracket\_content** ::= <any text not containing a [bracket\_close](#grammar-token-bracket_close)
of the same {len} as the [bracket\_open](#grammar-token-bracket_open)>
**bracket\_close** ::= ']' '='{len} ']'
```
An opening bracket of length *len >= 0* is written `[` followed by *len* `=` followed by `[` and the corresponding closing bracket is written `]` followed by *len* `=` followed by `]`. Brackets do not nest. A unique length may always be chosen for the opening and closing brackets to contain closing brackets of other lengths.
Bracket argument content consists of all text between the opening and closing brackets, except that one newline immediately following the opening bracket, if any, is ignored. No evaluation of the enclosed content, such as [Escape Sequences](#escape-sequences) or [Variable References](#variable-references), is performed. A bracket argument is always given to the command invocation as exactly one argument.
For example:
```
message([=[
This is the first line in a bracket argument with bracket length 1.
No \-escape sequences or ${variable} references are evaluated.
This is always one argument even though it contains a ; character.
The text does not end on a closing bracket of length 0 like ]].
It does end in a closing bracket of length 1.
]=])
```
Note
CMake versions prior to 3.0 do not support bracket arguments. They interpret the opening bracket as the start of an [Unquoted Argument](#unquoted-argument).
#### Quoted Argument
A *quoted argument* encloses content between opening and closing double-quote characters:
```
**quoted\_argument** ::= '"' [quoted\_element](#grammar-token-quoted_element)* '"'
**quoted\_element** ::= <any character except '\' or '"'> |
[escape\_sequence](#grammar-token-escape_sequence) |
[quoted\_continuation](#grammar-token-quoted_continuation)
**quoted\_continuation** ::= '\' [newline](#grammar-token-newline)
```
Quoted argument content consists of all text between opening and closing quotes. Both [Escape Sequences](#escape-sequences) and [Variable References](#variable-references) are evaluated. A quoted argument is always given to the command invocation as exactly one argument.
For example:
```
message("This is a quoted argument containing multiple lines.
This is always one argument even though it contains a ; character.
Both \\-escape sequences and ${variable} references are evaluated.
The text does not end on an escaped double-quote like \".
It does end in an unescaped double quote.
")
```
The final `\` on any line ending in an odd number of backslashes is treated as a line continuation and ignored along with the immediately following newline character. For example:
```
message("\
This is the first line of a quoted argument. \
In fact it is the only line but since it is long \
the source code uses line continuation.\
")
```
Note
CMake versions prior to 3.0 do not support continuation with `\`. They report errors in quoted arguments containing lines ending in an odd number of `\` characters.
#### Unquoted Argument
An *unquoted argument* is not enclosed by any quoting syntax. It may not contain any whitespace, `(`, `)`, `#`, `"`, or `\` except when escaped by a backslash:
```
**unquoted\_argument** ::= [unquoted\_element](#grammar-token-unquoted_element)+ | [unquoted\_legacy](#grammar-token-unquoted_legacy)
**unquoted\_element** ::= <any character except whitespace or one of '()#"\'> |
[escape\_sequence](#grammar-token-escape_sequence)
**unquoted\_legacy** ::= <see note in text>
```
Unquoted argument content consists of all text in a contiguous block of allowed or escaped characters. Both [Escape Sequences](#escape-sequences) and [Variable References](#variable-references) are evaluated. The resulting value is divided in the same way [Lists](#lists) divide into elements. Each non-empty element is given to the command invocation as an argument. Therefore an unquoted argument may be given to a command invocation as zero or more arguments.
For example:
```
foreach(arg
NoSpace
Escaped\ Space
This;Divides;Into;Five;Arguments
Escaped\;Semicolon
)
message("${arg}")
endforeach()
```
Note
To support legacy CMake code, unquoted arguments may also contain double-quoted strings (`"..."`, possibly enclosing horizontal whitespace), and make-style variable references (`$(MAKEVAR)`).
Unescaped double-quotes must balance, may not appear at the beginning of an unquoted argument, and are treated as part of the content. For example, the unquoted arguments `-Da="b c"`, `-Da=$(v)`, and `a" "b"c"d` are each interpreted literally.
Make-style references are treated literally as part of the content and do not undergo variable expansion. They are treated as part of a single argument (rather than as separate `$`, `(`, `MAKEVAR`, and `)` arguments).
The above “unquoted\_legacy” production represents such arguments. We do not recommend using legacy unquoted arguments in new code. Instead use a [Quoted Argument](#quoted-argument) or a [Bracket Argument](#bracket-argument) to represent the content.
### Escape Sequences
An *escape sequence* is a `\` followed by one character:
```
**escape\_sequence** ::= [escape\_identity](#grammar-token-escape_identity) | [escape\_encoded](#grammar-token-escape_encoded) | [escape\_semicolon](#grammar-token-escape_semicolon)
**escape\_identity** ::= '\' <match '[^A-Za-z0-9;]'>
**escape\_encoded** ::= '\t' | '\r' | '\n'
**escape\_semicolon** ::= '\;'
```
A `\` followed by a non-alphanumeric character simply encodes the literal character without interpreting it as syntax. A `\t`, `\r`, or `\n` encodes a tab, carriage return, or newline character, respectively. A `\;` outside of any [Variable References](#variable-references) encodes itself but may be used in an [Unquoted Argument](#unquoted-argument) to encode the `;` without dividing the argument value on it. A `\;` inside [Variable References](#variable-references) encodes the literal `;` character. (See also policy [`CMP0053`](../policy/cmp0053#policy:CMP0053 "CMP0053") documentation for historical considerations.)
### Variable References
A *variable reference* has the form `${variable_name}` and is evaluated inside a [Quoted Argument](#quoted-argument) or an [Unquoted Argument](#unquoted-argument). A variable reference is replaced by the value of the variable, or by the empty string if the variable is not set. Variable references can nest and are evaluated from the inside out, e.g. `${outer_${inner_variable}_variable}`.
Literal variable references may consist of alphanumeric characters, the characters `/_.+-`, and [Escape Sequences](#escape-sequences). Nested references may be used to evaluate variables of any name. (See also policy [`CMP0053`](../policy/cmp0053#policy:CMP0053 "CMP0053") documentation for historical considerations.)
The [Variables](#variables) section documents the scope of variable names and how their values are set.
An *environment variable reference* has the form `$ENV{VAR}` and is evaluated in the same contexts as a normal variable reference.
### Comments
A comment starts with a `#` character that is not inside a [Bracket Argument](#bracket-argument), [Quoted Argument](#quoted-argument), or escaped with `\` as part of an [Unquoted Argument](#unquoted-argument). There are two types of comments: a [Bracket Comment](#bracket-comment) and a [Line Comment](#line-comment).
#### Bracket Comment
A `#` immediately followed by a [Bracket Argument](#bracket-argument) forms a *bracket comment* consisting of the entire bracket enclosure:
```
**bracket\_comment** ::= '#' [bracket\_argument](#grammar-token-bracket_argument)
```
For example:
```
#[[This is a bracket comment.
It runs until the close bracket.]]
message("First Argument\n" #[[Bracket Comment]] "Second Argument")
```
Note
CMake versions prior to 3.0 do not support bracket comments. They interpret the opening `#` as the start of a [Line Comment](#line-comment).
#### Line Comment
A `#` not immediately followed by a [Bracket Argument](#bracket-argument) forms a *line comment* that runs until the end of the line:
```
**line\_comment** ::= '#' <any text not starting in a [bracket\_argument](#grammar-token-bracket_argument)
and not containing a [newline](#grammar-token-newline)>
```
For example:
```
# This is a line comment.
message("First Argument\n" # This is a line comment :)
"Second Argument") # This is a line comment.
```
Control Structures
------------------
### Conditional Blocks
The [`if()`](../command/if#command:if "if")/[`elseif()`](../command/elseif#command:elseif "elseif")/[`else()`](../command/else#command:else "else")/[`endif()`](../command/endif#command:endif "endif") commands delimit code blocks to be executed conditionally.
### Loops
The [`foreach()`](../command/foreach#command:foreach "foreach")/[`endforeach()`](../command/endforeach#command:endforeach "endforeach") and [`while()`](../command/while#command:while "while")/[`endwhile()`](../command/endwhile#command:endwhile "endwhile") commands delimit code blocks to be executed in a loop. Inside such blocks the [`break()`](../command/break#command:break "break") command may be used to terminate the loop early whereas the [`continue()`](../command/continue#command:continue "continue") command may be used to start with the next iteration immediately.
### Command Definitions
The [`macro()`](../command/macro#command:macro "macro")/[`endmacro()`](../command/endmacro#command:endmacro "endmacro"), and [`function()`](../command/function#command:function "function")/[`endfunction()`](../command/endfunction#command:endfunction "endfunction") commands delimit code blocks to be recorded for later invocation as commands.
Variables
---------
Variables are the basic unit of storage in the CMake Language. Their values are always of string type, though some commands may interpret the strings as values of other types. The [`set()`](../command/set#command:set "set") and [`unset()`](../command/unset#command:unset "unset") commands explicitly set or unset a variable, but other commands have semantics that modify variables as well. Variable names are case-sensitive and may consist of almost any text, but we recommend sticking to names consisting only of alphanumeric characters plus `_` and `-`.
Variables have dynamic scope. Each variable “set” or “unset” creates a binding in the current scope:
Function Scope
[Command Definitions](#command-definitions) created by the [`function()`](../command/function#command:function "function") command create commands that, when invoked, process the recorded commands in a new variable binding scope. A variable “set” or “unset” binds in this scope and is visible for the current function and any nested calls, but not after the function returns. Directory Scope
Each of the [Directories](#directories) in a source tree has its own variable bindings. Before processing the `CMakeLists.txt` file for a directory, CMake copies all variable bindings currently defined in the parent directory, if any, to initialize the new directory scope. CMake [Scripts](#scripts), when processed with `cmake -P`, bind variables in one “directory” scope.
A variable “set” or “unset” not inside a function call binds to the current directory scope.
Persistent Cache CMake stores a separate set of “cache” variables, or “cache entries”, whose values persist across multiple runs within a project build tree. Cache entries have an isolated binding scope modified only by explicit request, such as by the `CACHE` option of the [`set()`](../command/set#command:set "set") and [`unset()`](../command/unset#command:unset "unset") commands. When evaluating [Variable References](#variable-references), CMake first searches the function call stack, if any, for a binding and then falls back to the binding in the current directory scope, if any. If a “set” binding is found, its value is used. If an “unset” binding is found, or no binding is found, CMake then searches for a cache entry. If a cache entry is found, its value is used. Otherwise, the variable reference evaluates to an empty string.
The [`cmake-variables(7)`](cmake-variables.7#manual:cmake-variables(7) "cmake-variables(7)") manual documents many variables that are provided by CMake or have meaning to CMake when set by project code.
Lists
-----
Although all values in CMake are stored as strings, a string may be treated as a list in certain contexts, such as during evaluation of an [Unquoted Argument](#unquoted-argument). In such contexts, a string is divided into list elements by splitting on `;` characters not following an unequal number of `[` and `]` characters and not immediately preceded by a `\`. The sequence `\;` does not divide a value but is replaced by `;` in the resulting element.
A list of elements is represented as a string by concatenating the elements separated by `;`. For example, the [`set()`](../command/set#command:set "set") command stores multiple values into the destination variable as a list:
```
set(srcs a.c b.c c.c) # sets "srcs" to "a.c;b.c;c.c"
```
Lists are meant for simple use cases such as a list of source files and should not be used for complex data processing tasks. Most commands that construct lists do not escape `;` characters in list elements, thus flattening nested lists:
```
set(x a "b;c") # sets "x" to "a;b;c", not "a;b\;c"
```
| programming_docs |
cmake cmake-packages(7) cmake-packages(7)
=================
* [Introduction](#introduction)
* [Using Packages](#using-packages)
+ [Config-file Packages](#config-file-packages)
+ [Find-module Packages](#find-module-packages)
* [Package Layout](#package-layout)
+ [Package Configuration File](#package-configuration-file)
+ [Package Version File](#package-version-file)
* [Creating Packages](#creating-packages)
+ [Creating a Package Configuration File](#creating-a-package-configuration-file)
- [Creating a Package Configuration File for the Build Tree](#creating-a-package-configuration-file-for-the-build-tree)
+ [Creating Relocatable Packages](#creating-relocatable-packages)
* [Package Registry](#package-registry)
+ [User Package Registry](#user-package-registry)
+ [System Package Registry](#system-package-registry)
+ [Disabling the Package Registry](#disabling-the-package-registry)
+ [Package Registry Example](#package-registry-example)
+ [Package Registry Ownership](#package-registry-ownership)
Introduction
------------
Packages provide dependency information to CMake based buildsystems. Packages are found with the [`find_package()`](../command/find_package#command:find_package "find_package") command. The result of using `find_package` is either a set of [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets, or a set of variables corresponding to build-relevant information.
Using Packages
--------------
CMake provides direct support for two forms of packages, [Config-file Packages](#id1) and [Find-module Packages](#find-module-packages). Indirect support for `pkg-config` packages is also provided via the [`FindPkgConfig`](../module/findpkgconfig#module:FindPkgConfig "FindPkgConfig") module. In all cases, the basic form of [`find_package()`](../command/find_package#command:find_package "find_package") calls is the same:
```
find_package(Qt4 4.7.0 REQUIRED) # CMake provides a Qt4 find-module
find_package(Qt5Core 5.1.0 REQUIRED) # Qt provides a Qt5 package config file.
find_package(LibXml2 REQUIRED) # Use pkg-config via the LibXml2 find-module
```
In cases where it is known that a package configuration file is provided by upstream, and only that should be used, the `CONFIG` keyword may be passed to [`find_package()`](../command/find_package#command:find_package "find_package"):
```
find_package(Qt5Core 5.1.0 CONFIG REQUIRED)
find_package(Qt5Gui 5.1.0 CONFIG)
```
Similarly, the `MODULE` keyword says to use only a find-module:
```
find_package(Qt4 4.7.0 MODULE REQUIRED)
```
Specifying the type of package explicitly improves the error message shown to the user if it is not found.
Both types of packages also support specifying components of a package, either after the `REQUIRED` keyword:
```
find_package(Qt5 5.1.0 CONFIG REQUIRED Widgets Xml Sql)
```
or as a separate `COMPONENTS` list:
```
find_package(Qt5 5.1.0 COMPONENTS Widgets Xml Sql)
```
or as a separate `OPTIONAL_COMPONENTS` list:
```
find_package(Qt5 5.1.0 COMPONENTS Widgets
OPTIONAL_COMPONENTS Xml Sql
)
```
Handling of `COMPONENTS` and `OPTIONAL_COMPONENTS` is defined by the package.
By setting the [`CMAKE_DISABLE_FIND_PACKAGE_<PackageName>`](# "CMAKE_DISABLE_FIND_PACKAGE_<PackageName>") variable to `TRUE`, the `PackageName` package will not be searched, and will always be `NOTFOUND`.
### Config-file Packages
A config-file package is a set of files provided by upstreams for downstreams to use. CMake searches in a number of locations for package configuration files, as described in the [`find_package()`](../command/find_package#command:find_package "find_package") documentation. The most simple way for a CMake user to tell [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") to search in a non-standard prefix for a package is to set the `CMAKE_PREFIX_PATH` cache variable.
Config-file packages are provided by upstream vendors as part of development packages, that is, they belong with the header files and any other files provided to assist downstreams in using the package.
A set of variables which provide package status information are also set automatically when using a config-file package. The `<Package>_FOUND` variable is set to true or false, depending on whether the package was found. The `<Package>_DIR` cache variable is set to the location of the package configuration file.
### Find-module Packages
A find module is a file with a set of rules for finding the required pieces of a dependency, primarily header files and libraries. Typically, a find module is needed when the upstream is not built with CMake, or is not CMake-aware enough to otherwise provide a package configuration file. Unlike a package configuration file, it is not shipped with upstream, but is used by downstream to find the files by guessing locations of files with platform-specific hints.
Unlike the case of an upstream-provided package configuration file, no single point of reference identifies the package as being found, so the `<Package>_FOUND` variable is not automatically set by the [`find_package()`](../command/find_package#command:find_package "find_package") command. It can still be expected to be set by convention however and should be set by the author of the Find-module. Similarly there is no `<Package>_DIR` variable, but each of the artifacts such as library locations and header file locations provide a separate cache variable.
See the [`cmake-developer(7)`](cmake-developer.7#manual:cmake-developer(7) "cmake-developer(7)") manual for more information about creating Find-module files.
Package Layout
--------------
A config-file package consists of a [Package Configuration File](#package-configuration-file) and optionally a [Package Version File](#package-version-file) provided with the project distribution.
### Package Configuration File
Consider a project `Foo` that installs the following files:
```
<prefix>/include/foo-1.2/foo.h
<prefix>/lib/foo-1.2/libfoo.a
```
It may also provide a CMake package configuration file:
```
<prefix>/lib/cmake/foo-1.2/FooConfig.cmake
```
with content defining [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets, or defining variables, such as:
```
# ...
# (compute PREFIX relative to file location)
# ...
set(Foo_INCLUDE_DIRS ${PREFIX}/include/foo-1.2)
set(Foo_LIBRARIES ${PREFIX}/lib/foo-1.2/libfoo.a)
```
If another project wishes to use `Foo` it need only to locate the `FooConfig.cmake` file and load it to get all the information it needs about package content locations. Since the package configuration file is provided by the package installation it already knows all the file locations.
The [`find_package()`](../command/find_package#command:find_package "find_package") command may be used to search for the package configuration file. This command constructs a set of installation prefixes and searches under each prefix in several locations. Given the name `Foo`, it looks for a file called `FooConfig.cmake` or `foo-config.cmake`. The full set of locations is specified in the [`find_package()`](../command/find_package#command:find_package "find_package") command documentation. One place it looks is:
```
<prefix>/lib/cmake/Foo*/
```
where `Foo*` is a case-insensitive globbing expression. In our example the globbing expression will match `<prefix>/lib/cmake/foo-1.2` and the package configuration file will be found.
Once found, a package configuration file is immediately loaded. It, together with a package version file, contains all the information the project needs to use the package.
### Package Version File
When the [`find_package()`](../command/find_package#command:find_package "find_package") command finds a candidate package configuration file it looks next to it for a version file. The version file is loaded to test whether the package version is an acceptable match for the version requested. If the version file claims compatibility the configuration file is accepted. Otherwise it is ignored.
The name of the package version file must match that of the package configuration file but has either `-version` or `Version` appended to the name before the `.cmake` extension. For example, the files:
```
<prefix>/lib/cmake/foo-1.3/foo-config.cmake
<prefix>/lib/cmake/foo-1.3/foo-config-version.cmake
```
and:
```
<prefix>/lib/cmake/bar-4.2/BarConfig.cmake
<prefix>/lib/cmake/bar-4.2/BarConfigVersion.cmake
```
are each pairs of package configuration files and corresponding package version files.
When the [`find_package()`](../command/find_package#command:find_package "find_package") command loads a version file it first sets the following variables:
`PACKAGE_FIND_NAME` The <package> name
`PACKAGE_FIND_VERSION` Full requested version string
`PACKAGE_FIND_VERSION_MAJOR` Major version if requested, else 0
`PACKAGE_FIND_VERSION_MINOR` Minor version if requested, else 0
`PACKAGE_FIND_VERSION_PATCH` Patch version if requested, else 0
`PACKAGE_FIND_VERSION_TWEAK` Tweak version if requested, else 0
`PACKAGE_FIND_VERSION_COUNT` Number of version components, 0 to 4 The version file must use these variables to check whether it is compatible or an exact match for the requested version and set the following variables with results:
`PACKAGE_VERSION` Full provided version string
`PACKAGE_VERSION_EXACT` True if version is exact match
`PACKAGE_VERSION_COMPATIBLE` True if version is compatible
`PACKAGE_VERSION_UNSUITABLE` True if unsuitable as any version Version files are loaded in a nested scope so they are free to set any variables they wish as part of their computation. The find\_package command wipes out the scope when the version file has completed and it has checked the output variables. When the version file claims to be an acceptable match for the requested version the find\_package command sets the following variables for use by the project:
`<package>_VERSION` Full provided version string
`<package>_VERSION_MAJOR` Major version if provided, else 0
`<package>_VERSION_MINOR` Minor version if provided, else 0
`<package>_VERSION_PATCH` Patch version if provided, else 0
`<package>_VERSION_TWEAK` Tweak version if provided, else 0
`<package>_VERSION_COUNT` Number of version components, 0 to 4 The variables report the version of the package that was actually found. The `<package>` part of their name matches the argument given to the [`find_package()`](../command/find_package#command:find_package "find_package") command.
Creating Packages
-----------------
Usually, the upstream depends on CMake itself and can use some CMake facilities for creating the package files. Consider an upstream which provides a single shared library:
```
project(UpstreamLib)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)
set(Upstream_VERSION 3.4.1)
include(GenerateExportHeader)
add_library(ClimbingStats SHARED climbingstats.cpp)
generate_export_header(ClimbingStats)
set_property(TARGET ClimbingStats PROPERTY VERSION ${Upstream_VERSION})
set_property(TARGET ClimbingStats PROPERTY SOVERSION 3)
set_property(TARGET ClimbingStats PROPERTY
INTERFACE_ClimbingStats_MAJOR_VERSION 3)
set_property(TARGET ClimbingStats APPEND PROPERTY
COMPATIBLE_INTERFACE_STRING ClimbingStats_MAJOR_VERSION
)
install(TARGETS ClimbingStats EXPORT ClimbingStatsTargets
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
RUNTIME DESTINATION bin
INCLUDES DESTINATION include
)
install(
FILES
climbingstats.h
"${CMAKE_CURRENT_BINARY_DIR}/climbingstats_export.h"
DESTINATION
include
COMPONENT
Devel
)
include(CMakePackageConfigHelpers)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/ClimbingStats/ClimbingStatsConfigVersion.cmake"
VERSION ${Upstream_VERSION}
COMPATIBILITY AnyNewerVersion
)
export(EXPORT ClimbingStatsTargets
FILE "${CMAKE_CURRENT_BINARY_DIR}/ClimbingStats/ClimbingStatsTargets.cmake"
NAMESPACE Upstream::
)
configure_file(cmake/ClimbingStatsConfig.cmake
"${CMAKE_CURRENT_BINARY_DIR}/ClimbingStats/ClimbingStatsConfig.cmake"
COPYONLY
)
set(ConfigPackageLocation lib/cmake/ClimbingStats)
install(EXPORT ClimbingStatsTargets
FILE
ClimbingStatsTargets.cmake
NAMESPACE
Upstream::
DESTINATION
${ConfigPackageLocation}
)
install(
FILES
cmake/ClimbingStatsConfig.cmake
"${CMAKE_CURRENT_BINARY_DIR}/ClimbingStats/ClimbingStatsConfigVersion.cmake"
DESTINATION
${ConfigPackageLocation}
COMPONENT
Devel
)
```
The [`CMakePackageConfigHelpers`](../module/cmakepackageconfighelpers#module:CMakePackageConfigHelpers "CMakePackageConfigHelpers") module provides a macro for creating a simple `ConfigVersion.cmake` file. This file sets the version of the package. It is read by CMake when [`find_package()`](../command/find_package#command:find_package "find_package") is called to determine the compatibility with the requested version, and to set some version-specific variables `<Package>_VERSION`, `<Package>_VERSION_MAJOR`, `<Package>_VERSION_MINOR` etc. The [`install(EXPORT)`](../command/install#command:install "install") command is used to export the targets in the `ClimbingStatsTargets` export-set, defined previously by the [`install(TARGETS)`](../command/install#command:install "install") command. This command generates the `ClimbingStatsTargets.cmake` file to contain [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets, suitable for use by downstreams and arranges to install it to `lib/cmake/ClimbingStats`. The generated `ClimbingStatsConfigVersion.cmake` and a `cmake/ClimbingStatsConfig.cmake` are installed to the same location, completing the package.
The generated [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets have appropriate properties set to define their [usage requirements](cmake-buildsystem.7#target-usage-requirements), such as [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES"), [`INTERFACE_COMPILE_DEFINITIONS`](../prop_tgt/interface_compile_definitions#prop_tgt:INTERFACE_COMPILE_DEFINITIONS "INTERFACE_COMPILE_DEFINITIONS") and other relevant built-in `INTERFACE_` properties. The `INTERFACE` variant of user-defined properties listed in [`COMPATIBLE_INTERFACE_STRING`](../prop_tgt/compatible_interface_string#prop_tgt:COMPATIBLE_INTERFACE_STRING "COMPATIBLE_INTERFACE_STRING") and other [Compatible Interface Properties](cmake-buildsystem.7#compatible-interface-properties) are also propagated to the generated [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets. In the above case, `ClimbingStats_MAJOR_VERSION` is defined as a string which must be compatible among the dependencies of any depender. By setting this custom defined user property in this version and in the next version of `ClimbingStats`, [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") will issue a diagnostic if there is an attempt to use version 3 together with version 4. Packages can choose to employ such a pattern if different major versions of the package are designed to be incompatible.
A `NAMESPACE` with double-colons is specified when exporting the targets for installation. This convention of double-colons gives CMake a hint that the name is an [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target when it is used by downstreams with the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command. This way, CMake can issue a diagnostic if the package providing it has not yet been found.
In this case, when using [`install(TARGETS)`](../command/install#command:install "install") the `INCLUDES DESTINATION` was specified. This causes the `IMPORTED` targets to have their [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") populated with the `include` directory in the [`CMAKE_INSTALL_PREFIX`](../variable/cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX"). When the `IMPORTED` target is used by downstream, it automatically consumes the entries from that property.
### Creating a Package Configuration File
In this case, the `ClimbingStatsConfig.cmake` file could be as simple as:
```
include("${CMAKE_CURRENT_LIST_DIR}/ClimbingStatsTargets.cmake")
```
As this allows downstreams to use the `IMPORTED` targets. If any macros should be provided by the `ClimbingStats` package, they should be in a separate file which is installed to the same location as the `ClimbingStatsConfig.cmake` file, and included from there.
This can also be extended to cover dependencies:
```
# ...
add_library(ClimbingStats SHARED climbingstats.cpp)
generate_export_header(ClimbingStats)
find_package(Stats 2.6.4 REQUIRED)
target_link_libraries(ClimbingStats PUBLIC Stats::Types)
```
As the `Stats::Types` target is a `PUBLIC` dependency of `ClimbingStats`, downstreams must also find the `Stats` package and link to the `Stats::Types` library. The `Stats` package should be found in the `ClimbingStatsConfig.cmake` file to ensure this. The `find_dependency` macro from the [`CMakeFindDependencyMacro`](../module/cmakefinddependencymacro#module:CMakeFindDependencyMacro "CMakeFindDependencyMacro") helps with this by propagating whether the package is `REQUIRED`, or `QUIET` etc. All `REQUIRED` dependencies of a package should be found in the `Config.cmake` file:
```
include(CMakeFindDependencyMacro)
find_dependency(Stats 2.6.4)
include("${CMAKE_CURRENT_LIST_DIR}/ClimbingStatsTargets.cmake")
include("${CMAKE_CURRENT_LIST_DIR}/ClimbingStatsMacros.cmake")
```
The `find_dependency` macro also sets `ClimbingStats_FOUND` to `False` if the dependency is not found, along with a diagnostic that the `ClimbingStats` package can not be used without the `Stats` package.
If `COMPONENTS` are specified when the downstream uses [`find_package()`](../command/find_package#command:find_package "find_package"), they are listed in the `<Package>_FIND_COMPONENTS` variable. If a particular component is non-optional, then the `<Package>_FIND_REQUIRED_<comp>` will be true. This can be tested with logic in the package configuration file:
```
include(CMakeFindDependencyMacro)
find_dependency(Stats 2.6.4)
include("${CMAKE_CURRENT_LIST_DIR}/ClimbingStatsTargets.cmake")
include("${CMAKE_CURRENT_LIST_DIR}/ClimbingStatsMacros.cmake")
set(_supported_components Plot Table)
foreach(_comp ${ClimbingStats_FIND_COMPONENTS})
if (NOT ";${_supported_components};" MATCHES _comp)
set(ClimbingStats_FOUND False)
set(ClimbingStats_NOT_FOUND_MESSAGE "Unsupported component: ${_comp}")
endif()
include("${CMAKE_CURRENT_LIST_DIR}/ClimbingStats${_comp}Targets.cmake")
endforeach()
```
Here, the `ClimbingStats_NOT_FOUND_MESSAGE` is set to a diagnosis that the package could not be found because an invalid component was specified. This message variable can be set for any case where the `_FOUND` variable is set to `False`, and will be displayed to the user.
#### Creating a Package Configuration File for the Build Tree
The [`export(EXPORT)`](../command/export#command:export "export") command creates an [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") targets definition file which is specific to the build-tree, and is not relocatable. This can similarly be used with a suitable package configuration file and package version file to define a package for the build tree which may be used without installation. Consumers of the build tree can simply ensure that the [`CMAKE_PREFIX_PATH`](../variable/cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH") contains the build directory, or set the `ClimbingStats_DIR` to `<build_dir>/ClimbingStats` in the cache.
### Creating Relocatable Packages
A relocatable package must not reference absolute paths of files on the machine where the package is built that will not exist on the machines where the package may be installed.
Packages created by [`install(EXPORT)`](../command/install#command:install "install") are designed to be relocatable, using paths relative to the location of the package itself. When defining the interface of a target for `EXPORT`, keep in mind that the include directories should be specified as relative paths which are relative to the [`CMAKE_INSTALL_PREFIX`](../variable/cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX"):
```
target_include_directories(tgt INTERFACE
# Wrong, not relocatable:
$<INSTALL_INTERFACE:${CMAKE_INSTALL_PREFIX}/include/TgtName>
)
target_include_directories(tgt INTERFACE
# Ok, relocatable:
$<INSTALL_INTERFACE:include/TgtName>
)
```
The `$<INSTALL_PREFIX>` [`generator expression`](cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") may be used as a placeholder for the install prefix without resulting in a non-relocatable package. This is necessary if complex generator expressions are used:
```
target_include_directories(tgt INTERFACE
# Ok, relocatable:
$<INSTALL_INTERFACE:$<$<CONFIG:Debug>:$<INSTALL_PREFIX>/include/TgtName>>
)
```
This also applies to paths referencing external dependencies. It is not advisable to populate any properties which may contain paths, such as [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") and [`INTERFACE_LINK_LIBRARIES`](../prop_tgt/interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES"), with paths relevant to dependencies. For example, this code may not work well for a relocatable package:
```
target_link_libraries(ClimbingStats INTERFACE
${Foo_LIBRARIES} ${Bar_LIBRARIES}
)
target_include_directories(ClimbingStats INTERFACE
"$<INSTALL_INTERFACE:${Foo_INCLUDE_DIRS};${Bar_INCLUDE_DIRS}>"
)
```
The referenced variables may contain the absolute paths to libraries and include directories **as found on the machine the package was made on**. This would create a package with hard-coded paths to dependencies and not suitable for relocation.
Ideally such dependencies should be used through their own [IMPORTED targets](cmake-buildsystem.7#imported-targets) that have their own [`IMPORTED_LOCATION`](../prop_tgt/imported_location#prop_tgt:IMPORTED_LOCATION "IMPORTED_LOCATION") and usage requirement properties such as [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") populated appropriately. Those imported targets may then be used with the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command for `ClimbingStats`:
```
target_link_libraries(ClimbingStats INTERFACE Foo::Foo Bar::Bar)
```
With this approach the package references its external dependencies only through the names of [IMPORTED targets](cmake-buildsystem.7#imported-targets). When a consumer uses the installed package, the consumer will run the appropriate [`find_package()`](../command/find_package#command:find_package "find_package") commands (via the `find_dependency` macro described above) to find the dependencies and populate the imported targets with appropriate paths on their own machine.
Unfortunately many [`modules`](cmake-modules.7#manual:cmake-modules(7) "cmake-modules(7)") shipped with CMake do not yet provide [IMPORTED targets](cmake-buildsystem.7#imported-targets) because their development pre-dated this approach. This may improve incrementally over time. Workarounds to create relocatable packages using such modules include:
* When building the package, specify each `Foo_LIBRARY` cache entry as just a library name, e.g. `-DFoo_LIBRARY=foo`. This tells the corresponding find module to populate the `Foo_LIBRARIES` with just `foo` to ask the linker to search for the library instead of hard-coding a path.
* Or, after installing the package content but before creating the package installation binary for redistribution, manually replace the absolute paths with placeholders for substitution by the installation tool when the package is installed.
Package Registry
----------------
CMake provides two central locations to register packages that have been built or installed anywhere on a system:
* [User Package Registry](#user-package-registry)
* [System Package Registry](#system-package-registry)
The registries are especially useful to help projects find packages in non-standard install locations or directly in their own build trees. A project may populate either the user or system registry (using its own means, see below) to refer to its location. In either case the package should store at the registered location a [Package Configuration File](#package-configuration-file) (`<package>Config.cmake`) and optionally a [Package Version File](#package-version-file) (`<package>ConfigVersion.cmake`).
The [`find_package()`](../command/find_package#command:find_package "find_package") command searches the two package registries as two of the search steps specified in its documentation. If it has sufficient permissions it also removes stale package registry entries that refer to directories that do not exist or do not contain a matching package configuration file.
### User Package Registry
The User Package Registry is stored in a per-user location. The [`export(PACKAGE)`](../command/export#command:export "export") command may be used to register a project build tree in the user package registry. CMake currently provides no interface to add install trees to the user package registry. Installers must be manually taught to register their packages if desired.
On Windows the user package registry is stored in the Windows registry under a key in `HKEY_CURRENT_USER`.
A `<package>` may appear under registry key:
```
HKEY_CURRENT_USER\Software\Kitware\CMake\Packages\<package>
```
as a `REG_SZ` value, with arbitrary name, that specifies the directory containing the package configuration file.
On UNIX platforms the user package registry is stored in the user home directory under `~/.cmake/packages`. A `<package>` may appear under the directory:
```
~/.cmake/packages/<package>
```
as a file, with arbitrary name, whose content specifies the directory containing the package configuration file.
### System Package Registry
The System Package Registry is stored in a system-wide location. CMake currently provides no interface to add to the system package registry. Installers must be manually taught to register their packages if desired.
On Windows the system package registry is stored in the Windows registry under a key in `HKEY_LOCAL_MACHINE`. A `<package>` may appear under registry key:
```
HKEY_LOCAL_MACHINE\Software\Kitware\CMake\Packages\<package>
```
as a `REG_SZ` value, with arbitrary name, that specifies the directory containing the package configuration file.
There is no system package registry on non-Windows platforms.
### Disabling the Package Registry
In some cases using the Package Registries is not desirable. CMake allows one to disable them using the following variables:
* [`CMAKE_EXPORT_NO_PACKAGE_REGISTRY`](../variable/cmake_export_no_package_registry#variable:CMAKE_EXPORT_NO_PACKAGE_REGISTRY "CMAKE_EXPORT_NO_PACKAGE_REGISTRY") disables the [`export(PACKAGE)`](../command/export#command:export "export") command.
* [`CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY`](../variable/cmake_find_package_no_package_registry#variable:CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY "CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY") disables the User Package Registry in all the [`find_package()`](../command/find_package#command:find_package "find_package") calls.
* [`CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY`](../variable/cmake_find_package_no_system_package_registry#variable:CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY "CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY") disables the System Package Registry in all the [`find_package()`](../command/find_package#command:find_package "find_package") calls.
### Package Registry Example
A simple convention for naming package registry entries is to use content hashes. They are deterministic and unlikely to collide ([`export(PACKAGE)`](../command/export#command:export "export") uses this approach). The name of an entry referencing a specific directory is simply the content hash of the directory path itself.
If a project arranges for package registry entries to exist, such as:
```
> reg query HKCU\Software\Kitware\CMake\Packages\MyPackage
HKEY_CURRENT_USER\Software\Kitware\CMake\Packages\MyPackage
45e7d55f13b87179bb12f907c8de6fc4 REG_SZ c:/Users/Me/Work/lib/cmake/MyPackage
7b4a9844f681c80ce93190d4e3185db9 REG_SZ c:/Users/Me/Work/MyPackage-build
```
or:
```
$ cat ~/.cmake/packages/MyPackage/7d1fb77e07ce59a81bed093bbee945bd
/home/me/work/lib/cmake/MyPackage
$ cat ~/.cmake/packages/MyPackage/f92c1db873a1937f3100706657c63e07
/home/me/work/MyPackage-build
```
then the `CMakeLists.txt` code:
```
find_package(MyPackage)
```
will search the registered locations for package configuration files (`MyPackageConfig.cmake`). The search order among package registry entries for a single package is unspecified and the entry names (hashes in this example) have no meaning. Registered locations may contain package version files (`MyPackageConfigVersion.cmake`) to tell [`find_package()`](../command/find_package#command:find_package "find_package") whether a specific location is suitable for the version requested.
### Package Registry Ownership
Package registry entries are individually owned by the project installations that they reference. A package installer is responsible for adding its own entry and the corresponding uninstaller is responsible for removing it.
The [`export(PACKAGE)`](../command/export#command:export "export") command populates the user package registry with the location of a project build tree. Build trees tend to be deleted by developers and have no “uninstall” event that could trigger removal of their entries. In order to keep the registries clean the [`find_package()`](../command/find_package#command:find_package "find_package") command automatically removes stale entries it encounters if it has sufficient permissions. CMake provides no interface to remove an entry referencing an existing build tree once [`export(PACKAGE)`](../command/export#command:export "export") has been invoked. However, if the project removes its package configuration file from the build tree then the entry referencing the location will be considered stale.
| programming_docs |
cmake cmake-compile-features(7) cmake-compile-features(7)
=========================
* [Introduction](#introduction)
* [Compile Feature Requirements](#compile-feature-requirements)
+ [Requiring Language Standards](#requiring-language-standards)
+ [Availability of Compiler Extensions](#availability-of-compiler-extensions)
* [Optional Compile Features](#optional-compile-features)
* [Conditional Compilation Options](#conditional-compilation-options)
* [Supported Compilers](#supported-compilers)
Introduction
------------
Project source code may depend on, or be conditional on, the availability of certain features of the compiler. There are three use-cases which arise: [Compile Feature Requirements](#compile-feature-requirements), [Optional Compile Features](#optional-compile-features) and [Conditional Compilation Options](#conditional-compilation-options).
While features are typically specified in programming language standards, CMake provides a primary user interface based on granular handling of the features, not the language standard that introduced the feature.
The [`CMAKE_C_KNOWN_FEATURES`](../prop_gbl/cmake_c_known_features#prop_gbl:CMAKE_C_KNOWN_FEATURES "CMAKE_C_KNOWN_FEATURES") and [`CMAKE_CXX_KNOWN_FEATURES`](../prop_gbl/cmake_cxx_known_features#prop_gbl:CMAKE_CXX_KNOWN_FEATURES "CMAKE_CXX_KNOWN_FEATURES") global properties contain all the features known to CMake, regardless of compiler support for the feature. The [`CMAKE_C_COMPILE_FEATURES`](../variable/cmake_c_compile_features#variable:CMAKE_C_COMPILE_FEATURES "CMAKE_C_COMPILE_FEATURES") and [`CMAKE_CXX_COMPILE_FEATURES`](../variable/cmake_cxx_compile_features#variable:CMAKE_CXX_COMPILE_FEATURES "CMAKE_CXX_COMPILE_FEATURES") variables contain all features CMake knows are known to the compiler, regardless of language standard or compile flags needed to use them.
Features known to CMake are named mostly following the same convention as the Clang feature test macros. The are some exceptions, such as CMake using `cxx_final` and `cxx_override` instead of the single `cxx_override_control` used by Clang.
Compile Feature Requirements
----------------------------
Compile feature requirements may be specified with the [`target_compile_features()`](../command/target_compile_features#command:target_compile_features "target_compile_features") command. For example, if a target must be compiled with compiler support for the [`cxx_constexpr`](../prop_gbl/cmake_cxx_known_features#prop_gbl:CMAKE_CXX_KNOWN_FEATURES "CMAKE_CXX_KNOWN_FEATURES") feature:
```
add_library(mylib requires_constexpr.cpp)
target_compile_features(mylib PRIVATE cxx_constexpr)
```
In processing the requirement for the `cxx_constexpr` feature, [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") will ensure that the in-use C++ compiler is capable of the feature, and will add any necessary flags such as `-std=gnu++11` to the compile lines of C++ files in the `mylib` target. A `FATAL_ERROR` is issued if the compiler is not capable of the feature.
The exact compile flags and language standard are deliberately not part of the user interface for this use-case. CMake will compute the appropriate compile flags to use by considering the features specified for each target.
Such compile flags are added even if the compiler supports the particular feature without the flag. For example, the GNU compiler supports variadic templates (with a warning) even if `-std=gnu++98` is used. CMake adds the `-std=gnu++11` flag if `cxx_variadic_templates` is specified as a requirement.
In the above example, `mylib` requires `cxx_constexpr` when it is built itself, but consumers of `mylib` are not required to use a compiler which supports `cxx_constexpr`. If the interface of `mylib` does require the `cxx_constexpr` feature (or any other known feature), that may be specified with the `PUBLIC` or `INTERFACE` signatures of [`target_compile_features()`](../command/target_compile_features#command:target_compile_features "target_compile_features"):
```
add_library(mylib requires_constexpr.cpp)
# cxx_constexpr is a usage-requirement
target_compile_features(mylib PUBLIC cxx_constexpr)
# main.cpp will be compiled with -std=gnu++11 on GNU for cxx_constexpr.
add_executable(myexe main.cpp)
target_link_libraries(myexe mylib)
```
Feature requirements are evaluated transitively by consuming the link implementation. See [`cmake-buildsystem(7)`](cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") for more on transitive behavior of build properties and usage requirements.
### Requiring Language Standards
In projects that use a large number of commonly available features from a particular language standard (e.g. C++ 11) one may specify a meta-feature (e.g. `cxx_std_11`) that requires use of a compiler mode aware of that standard. This is simpler than specifying all the features individually, but does not guarantee the existence of any particular feature. Diagnosis of use of unsupported features will be delayed until compile time.
For example, if C++ 11 features are used extensively in a project’s header files, then clients must use a compiler mode aware of C++ 11 or above. This can be requested with the code:
```
target_compile_features(mylib PUBLIC cxx_std_11)
```
In this example, CMake will ensure the compiler is invoked in a mode that is aware of C++ 11 (or above), adding flags such as `-std=gnu++11` if necessary. This applies to sources within `mylib` as well as any dependents (that may include headers from `mylib`).
### Availability of Compiler Extensions
Because the [`CXX_EXTENSIONS`](../prop_tgt/cxx_extensions#prop_tgt:CXX_EXTENSIONS "CXX_EXTENSIONS") target property is `ON` by default, CMake uses extended variants of language dialects by default, such as `-std=gnu++11` instead of `-std=c++11`. That target property may be set to `OFF` to use the non-extended variant of the dialect flag. Note that because most compilers enable extensions by default, this could expose cross-platform bugs in user code or in the headers of third-party dependencies.
Optional Compile Features
-------------------------
Compile features may be preferred if available, without creating a hard requirement. For example, a library may provides alternative implementations depending on whether the `cxx_variadic_templates` feature is available:
```
#if Foo_COMPILER_CXX_VARIADIC_TEMPLATES
template<int I, int... Is>
struct Interface;
template<int I>
struct Interface<I>
{
static int accumulate()
{
return I;
}
};
template<int I, int... Is>
struct Interface
{
static int accumulate()
{
return I + Interface<Is...>::accumulate();
}
};
#else
template<int I1, int I2 = 0, int I3 = 0, int I4 = 0>
struct Interface
{
static int accumulate() { return I1 + I2 + I3 + I4; }
};
#endif
```
Such an interface depends on using the correct preprocessor defines for the compiler features. CMake can generate a header file containing such defines using the [`WriteCompilerDetectionHeader`](../module/writecompilerdetectionheader#module:WriteCompilerDetectionHeader "WriteCompilerDetectionHeader") module. The module contains the `write_compiler_detection_header` function which accepts parameters to control the content of the generated header file:
```
write_compiler_detection_header(
FILE "${CMAKE_CURRENT_BINARY_DIR}/foo_compiler_detection.h"
PREFIX Foo
COMPILERS GNU
FEATURES
cxx_variadic_templates
)
```
Such a header file may be used internally in the source code of a project, and it may be installed and used in the interface of library code.
For each feature listed in `FEATURES`, a preprocessor definition is created in the header file, and defined to either `1` or `0`.
Additionally, some features call for additional defines, such as the `cxx_final` and `cxx_override` features. Rather than being used in `#ifdef` code, the `final` keyword is abstracted by a symbol which is defined to either `final`, a compiler-specific equivalent, or to empty. That way, C++ code can be written to unconditionally use the symbol, and compiler support determines what it is expanded to:
```
struct Interface {
virtual void Execute() = 0;
};
struct Concrete Foo_FINAL {
void Execute() Foo_OVERRIDE;
};
```
In this case, `Foo_FINAL` will expand to `final` if the compiler supports the keyword, or to empty otherwise.
In this use-case, the CMake code will wish to enable a particular language standard if available from the compiler. The [`CXX_STANDARD`](../prop_tgt/cxx_standard#prop_tgt:CXX_STANDARD "CXX_STANDARD") target property variable may be set to the desired language standard for a particular target, and the [`CMAKE_CXX_STANDARD`](../variable/cmake_cxx_standard#variable:CMAKE_CXX_STANDARD "CMAKE_CXX_STANDARD") may be set to influence all following targets:
```
write_compiler_detection_header(
FILE "${CMAKE_CURRENT_BINARY_DIR}/foo_compiler_detection.h"
PREFIX Foo
COMPILERS GNU
FEATURES
cxx_final cxx_override
)
# Includes foo_compiler_detection.h and uses the Foo_FINAL symbol
# which will expand to 'final' if the compiler supports the requested
# CXX_STANDARD.
add_library(foo foo.cpp)
set_property(TARGET foo PROPERTY CXX_STANDARD 11)
# Includes foo_compiler_detection.h and uses the Foo_FINAL symbol
# which will expand to 'final' if the compiler supports the feature,
# even though CXX_STANDARD is not set explicitly. The requirement of
# cxx_constexpr causes CMake to set CXX_STANDARD internally, which
# affects the compile flags.
add_library(foo_impl foo_impl.cpp)
target_compile_features(foo_impl PRIVATE cxx_constexpr)
```
The `write_compiler_detection_header` function also creates compatibility code for other features which have standard equivalents. For example, the `cxx_static_assert` feature is emulated with a template and abstracted via the `<PREFIX>_STATIC_ASSERT` and `<PREFIX>_STATIC_ASSERT_MSG` function-macros.
Conditional Compilation Options
-------------------------------
Libraries may provide entirely different header files depending on requested compiler features.
For example, a header at `with_variadics/interface.h` may contain:
```
template<int I, int... Is>
struct Interface;
template<int I>
struct Interface<I>
{
static int accumulate()
{
return I;
}
};
template<int I, int... Is>
struct Interface
{
static int accumulate()
{
return I + Interface<Is...>::accumulate();
}
};
```
while a header at `no_variadics/interface.h` may contain:
```
template<int I1, int I2 = 0, int I3 = 0, int I4 = 0>
struct Interface
{
static int accumulate() { return I1 + I2 + I3 + I4; }
};
```
It would be possible to write a abstraction `interface.h` header containing something like:
```
#include "foo_compiler_detection.h"
#if Foo_COMPILER_CXX_VARIADIC_TEMPLATES
#include "with_variadics/interface.h"
#else
#include "no_variadics/interface.h"
#endif
```
However this could be unmaintainable if there are many files to abstract. What is needed is to use alternative include directories depending on the compiler capabilities.
CMake provides a `COMPILE_FEATURES` [`generator expression`](cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") to implement such conditions. This may be used with the build-property commands such as [`target_include_directories()`](../command/target_include_directories#command:target_include_directories "target_include_directories") and [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") to set the appropriate [`buildsystem`](cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") properties:
```
add_library(foo INTERFACE)
set(with_variadics ${CMAKE_CURRENT_SOURCE_DIR}/with_variadics)
set(no_variadics ${CMAKE_CURRENT_SOURCE_DIR}/no_variadics)
target_include_directories(foo
INTERFACE
"$<$<COMPILE_FEATURES:cxx_variadic_templates>:${with_variadics}>"
"$<$<NOT:$<COMPILE_FEATURES:cxx_variadic_templates>>:${no_variadics}>"
)
```
Consuming code then simply links to the `foo` target as usual and uses the feature-appropriate include directory
```
add_executable(consumer_with consumer_with.cpp)
target_link_libraries(consumer_with foo)
set_property(TARGET consumer_with CXX_STANDARD 11)
add_executable(consumer_no consumer_no.cpp)
target_link_libraries(consumer_no foo)
```
Supported Compilers
-------------------
CMake is currently aware of the [`C++ standards`](../prop_tgt/cxx_standard#prop_tgt:CXX_STANDARD "CXX_STANDARD") and [`compile features`](../prop_gbl/cmake_cxx_known_features#prop_gbl:CMAKE_CXX_KNOWN_FEATURES "CMAKE_CXX_KNOWN_FEATURES") available from the following [`compiler ids`](# "CMAKE_<LANG>_COMPILER_ID") as of the versions specified for each:
* `AppleClang`: Apple Clang for Xcode versions 4.4 though 6.2.
* `Clang`: Clang compiler versions 2.9 through 3.4.
* `GNU`: GNU compiler versions 4.4 through 5.0.
* `MSVC`: Microsoft Visual Studio versions 2010 through 2017.
* `SunPro`: Oracle SolarisStudio versions 12.4 through 12.5.
* `Intel`: Intel compiler versions 12.1 through 17.0.
CMake is currently aware of the [`C standards`](../prop_tgt/c_standard#prop_tgt:C_STANDARD "C_STANDARD") and [`compile features`](../prop_gbl/cmake_c_known_features#prop_gbl:CMAKE_C_KNOWN_FEATURES "CMAKE_C_KNOWN_FEATURES") available from the following [`compiler ids`](# "CMAKE_<LANG>_COMPILER_ID") as of the versions specified for each:
* all compilers and versions listed above for C++.
* `GNU`: GNU compiler versions 3.4 through 5.0.
CMake is currently aware of the [`C++ standards`](../prop_tgt/cxx_standard#prop_tgt:CXX_STANDARD "CXX_STANDARD") and their associated meta-features (e.g. `cxx_std_11`) available from the following [`compiler ids`](# "CMAKE_<LANG>_COMPILER_ID") as of the versions specified for each:
* `Cray`: Cray Compiler Environment version 8.1 through 8.5.8.
* `PGI`: PGI version 12.10 through 17.5.
* `XL`: IBM XL version 10.1 through 13.1.5.
CMake is currently aware of the [`C standards`](../prop_tgt/c_standard#prop_tgt:C_STANDARD "C_STANDARD") and their associated meta-features (e.g. `c_std_99`) available from the following [`compiler ids`](# "CMAKE_<LANG>_COMPILER_ID") as of the versions specified for each:
* all compilers and versions listed above with only meta-features for C++.
CMake is currently aware of the [`CUDA standards`](../prop_tgt/cuda_standard#prop_tgt:CUDA_STANDARD "CUDA_STANDARD") from the following [`compiler ids`](# "CMAKE_<LANG>_COMPILER_ID") as of the versions specified for each:
* `NVIDIA`: NVIDIA nvcc compiler 7.5 though 8.0.
cmake cmake(1) cmake(1)
========
Synopsis
--------
```
cmake [<options>] (<path-to-source> | <path-to-existing-build>)
cmake [(-D <var>=<value>)...] -P <cmake-script-file>
cmake --build <dir> [<options>...] [-- <build-tool-options>...]
cmake -E <command> [<options>...]
cmake --find-package <options>...
```
Description
-----------
The “cmake” executable is the CMake command-line interface. It may be used to configure projects in scripts. Project configuration settings may be specified on the command line with the -D option.
CMake is a cross-platform build system generator. Projects specify their build process with platform-independent CMake listfiles included in each directory of a source tree with the name CMakeLists.txt. Users build a project by using CMake to generate a build system for a native tool on their platform.
Options
-------
`-C <initial-cache>`
Pre-load a script to populate the cache.
When cmake is first run in an empty build tree, it creates a CMakeCache.txt file and populates it with customizable settings for the project. This option may be used to specify a file from which to load cache entries before the first pass through the project’s cmake listfiles. The loaded entries take priority over the project’s default values. The given file should be a CMake script containing SET commands that use the CACHE option, not a cache-format file.
`-D <var>:<type>=<value>, -D <var>=<value>`
Create a cmake cache entry.
When cmake is first run in an empty build tree, it creates a CMakeCache.txt file and populates it with customizable settings for the project. This option may be used to specify a setting that takes priority over the project’s default value. The option may be repeated for as many cache entries as desired.
If the `:<type>` portion is given it must be one of the types specified by the [`set()`](../command/set#command:set "set") command documentation for its `CACHE` signature. If the `:<type>` portion is omitted the entry will be created with no type if it does not exist with a type already. If a command in the project sets the type to `PATH` or `FILEPATH` then the `<value>` will be converted to an absolute path.
This option may also be given as a single argument: `-D<var>:<type>=<value>` or `-D<var>=<value>`.
`-U <globbing_expr>`
Remove matching entries from CMake cache.
This option may be used to remove one or more variables from the CMakeCache.txt file, globbing expressions using \* and ? are supported. The option may be repeated for as many cache entries as desired.
Use with care, you can make your CMakeCache.txt non-working.
`-G <generator-name>`
Specify a build system generator.
CMake may support multiple native build systems on certain platforms. A generator is responsible for generating a particular build system. Possible generator names are specified in the [`cmake-generators(7)`](cmake-generators.7#manual:cmake-generators(7) "cmake-generators(7)") manual.
`-T <toolset-spec>`
Toolset specification for the generator, if supported.
Some CMake generators support a toolset specification to tell the native build system how to choose a compiler. See the [`CMAKE_GENERATOR_TOOLSET`](../variable/cmake_generator_toolset#variable:CMAKE_GENERATOR_TOOLSET "CMAKE_GENERATOR_TOOLSET") variable for details.
`-A <platform-name>`
Specify platform name if supported by generator.
Some CMake generators support a platform name to be given to the native build system to choose a compiler or SDK. See the [`CMAKE_GENERATOR_PLATFORM`](../variable/cmake_generator_platform#variable:CMAKE_GENERATOR_PLATFORM "CMAKE_GENERATOR_PLATFORM") variable for details.
`-Wno-dev`
Suppress developer warnings.
Suppress warnings that are meant for the author of the CMakeLists.txt files. By default this will also turn off deprecation warnings.
`-Wdev`
Enable developer warnings.
Enable warnings that are meant for the author of the CMakeLists.txt files. By default this will also turn on deprecation warnings.
`-Werror=dev`
Make developer warnings errors.
Make warnings that are meant for the author of the CMakeLists.txt files errors. By default this will also turn on deprecated warnings as errors.
`-Wno-error=dev`
Make developer warnings not errors.
Make warnings that are meant for the author of the CMakeLists.txt files not errors. By default this will also turn off deprecated warnings as errors.
`-Wdeprecated`
Enable deprecated functionality warnings.
Enable warnings for usage of deprecated functionality, that are meant for the author of the CMakeLists.txt files.
`-Wno-deprecated`
Suppress deprecated functionality warnings.
Suppress warnings for usage of deprecated functionality, that are meant for the author of the CMakeLists.txt files.
`-Werror=deprecated`
Make deprecated macro and function warnings errors.
Make warnings for usage of deprecated macros and functions, that are meant for the author of the CMakeLists.txt files, errors.
`-Wno-error=deprecated`
Make deprecated macro and function warnings not errors.
Make warnings for usage of deprecated macros and functions, that are meant for the author of the CMakeLists.txt files, not errors.
`-E <command> [<options>...]` See [Command-Line Tool Mode](#command-line-tool-mode).
`-L[A][H]`
List non-advanced cached variables.
List cache variables will run CMake and list all the variables from the CMake cache that are not marked as INTERNAL or ADVANCED. This will effectively display current CMake settings, which can then be changed with -D option. Changing some of the variables may result in more variables being created. If A is specified, then it will display also advanced variables. If H is specified, it will also display help for each variable.
`--build <dir>` See [Build Tool Mode](#build-tool-mode).
`-N`
View mode only.
Only load the cache. Do not actually run configure and generate steps.
`-P <file>`
Process script mode.
Process the given cmake file as a script written in the CMake language. No configure or generate step is performed and the cache is not modified. If variables are defined using -D, this must be done before the -P argument.
`--find-package` See [Find-Package Tool Mode](#find-package-tool-mode).
`--graphviz=[file]`
Generate graphviz of dependencies, see CMakeGraphVizOptions.cmake for more.
Generate a graphviz input file that will contain all the library and executable dependencies in the project. See the documentation for CMakeGraphVizOptions.cmake for more details.
`--system-information [file]`
Dump information about this system.
Dump a wide range of information about the current system. If run from the top of a binary tree for a CMake project it will dump additional information such as the cache, log files etc.
`--debug-trycompile`
Do not delete the try\_compile build tree. Only useful on one try\_compile at a time.
Do not delete the files and directories created for try\_compile calls. This is useful in debugging failed try\_compiles. It may however change the results of the try-compiles as old junk from a previous try-compile may cause a different test to either pass or fail incorrectly. This option is best used for one try-compile at a time, and only when debugging.
`--debug-output`
Put cmake in a debug mode.
Print extra information during the cmake run like stack traces with message(send\_error ) calls.
`--trace`
Put cmake in trace mode.
Print a trace of all calls made and from where.
`--trace-expand`
Put cmake in trace mode.
Like `--trace`, but with variables expanded.
`--trace-source=<file>`
Put cmake in trace mode, but output only lines of a specified file.
Multiple options are allowed.
`--warn-uninitialized`
Warn about uninitialized values.
Print a warning when an uninitialized variable is used.
`--warn-unused-vars`
Warn about unused variables.
Find variables that are declared or set, but not used.
`--no-warn-unused-cli`
Don’t warn about command line options.
Don’t find variables that are declared on the command line, but not used.
`--check-system-vars`
Find problems with variable usage in system files.
Normally, unused and uninitialized variables are searched for only in CMAKE\_SOURCE\_DIR and CMAKE\_BINARY\_DIR. This flag tells CMake to warn about other files as well.
`--help,-help,-usage,-h,-H,/?`
Print usage information and exit.
Usage describes the basic command line interface and its options.
`--version,-version,/V [<f>]`
Show program name/version banner and exit.
If a file is specified, the version is written into it. The help is printed to a named <f>ile if given.
`--help-full [<f>]`
Print all help manuals and exit.
All manuals are printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-manual <man> [<f>]`
Print one help manual and exit.
The specified manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-manual-list [<f>]`
List help manuals available and exit.
The list contains all manuals for which help may be obtained by using the `--help-manual` option followed by a manual name. The help is printed to a named <f>ile if given.
`--help-command <cmd> [<f>]`
Print help for one command and exit.
The [`cmake-commands(7)`](cmake-commands.7#manual:cmake-commands(7) "cmake-commands(7)") manual entry for `<cmd>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-command-list [<f>]`
List commands with help available and exit.
The list contains all commands for which help may be obtained by using the `--help-command` option followed by a command name. The help is printed to a named <f>ile if given.
`--help-commands [<f>]`
Print cmake-commands manual and exit.
The [`cmake-commands(7)`](cmake-commands.7#manual:cmake-commands(7) "cmake-commands(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-module <mod> [<f>]`
Print help for one module and exit.
The [`cmake-modules(7)`](cmake-modules.7#manual:cmake-modules(7) "cmake-modules(7)") manual entry for `<mod>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-module-list [<f>]`
List modules with help available and exit.
The list contains all modules for which help may be obtained by using the `--help-module` option followed by a module name. The help is printed to a named <f>ile if given.
`--help-modules [<f>]`
Print cmake-modules manual and exit.
The [`cmake-modules(7)`](cmake-modules.7#manual:cmake-modules(7) "cmake-modules(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-policy <cmp> [<f>]`
Print help for one policy and exit.
The [`cmake-policies(7)`](cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") manual entry for `<cmp>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-policy-list [<f>]`
List policies with help available and exit.
The list contains all policies for which help may be obtained by using the `--help-policy` option followed by a policy name. The help is printed to a named <f>ile if given.
`--help-policies [<f>]`
Print cmake-policies manual and exit.
The [`cmake-policies(7)`](cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-property <prop> [<f>]`
Print help for one property and exit.
The [`cmake-properties(7)`](cmake-properties.7#manual:cmake-properties(7) "cmake-properties(7)") manual entries for `<prop>` are printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-property-list [<f>]`
List properties with help available and exit.
The list contains all properties for which help may be obtained by using the `--help-property` option followed by a property name. The help is printed to a named <f>ile if given.
`--help-properties [<f>]`
Print cmake-properties manual and exit.
The [`cmake-properties(7)`](cmake-properties.7#manual:cmake-properties(7) "cmake-properties(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-variable <var> [<f>]`
Print help for one variable and exit.
The [`cmake-variables(7)`](cmake-variables.7#manual:cmake-variables(7) "cmake-variables(7)") manual entry for `<var>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-variable-list [<f>]`
List variables with help available and exit.
The list contains all variables for which help may be obtained by using the `--help-variable` option followed by a variable name. The help is printed to a named <f>ile if given.
`--help-variables [<f>]`
Print cmake-variables manual and exit.
The [`cmake-variables(7)`](cmake-variables.7#manual:cmake-variables(7) "cmake-variables(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
Build Tool Mode
---------------
CMake provides a command-line signature to build an already-generated project binary tree:
```
cmake --build <dir> [<options>...] [-- <build-tool-options>...]
```
This abstracts a native build tool’s command-line interface with the following options:
`--build <dir>` Project binary directory to be built. This is required and must be first.
`--target <tgt>` Build `<tgt>` instead of default targets. May only be specified once.
`--config <cfg>` For multi-configuration tools, choose configuration `<cfg>`.
`--clean-first` Build target `clean` first, then build. (To clean only, use `--target clean`.)
`--use-stderr` Ignored. Behavior is default in CMake >= 3.0.
`--` Pass remaining options to the native tool. Run `cmake --build` with no options for quick help.
Command-Line Tool Mode
----------------------
CMake provides builtin command-line tools through the signature:
```
cmake -E <command> [<options>...]
```
Run `cmake -E` or `cmake -E help` for a summary of commands. Available commands are:
`capabilities`
Report cmake capabilities in JSON format. The output is a JSON object with the following keys:
`version`
A JSON object with version information. Keys are:
`string` The full version string as displayed by cmake `--version`.
`major` The major version number in integer form.
`minor` The minor version number in integer form.
`patch` The patch level in integer form.
`suffix` The cmake version suffix string.
`isDirty` A bool that is set if the cmake build is from a dirty tree.
`generators`
A list available generators. Each generator is a JSON object with the following keys:
`name` A string containing the name of the generator.
`toolsetSupport`
`true` if the generator supports toolsets and `false` otherwise.
`platformSupport`
`true` if the generator supports platforms and `false` otherwise.
`extraGenerators` A list of strings with all the extra generators compatible with the generator.
`serverMode`
`true` if cmake supports server-mode and `false` otherwise.
`chdir <dir> <cmd> [<arg>...]` Change the current working directory and run a command.
`compare_files <file1> <file2>` Check if `<file1>` is same as `<file2>`. If files are the same, then returns 0, if not it returns 1.
`copy <file>... <destination>` Copy files to `<destination>` (either file or directory). If multiple files are specified, the `<destination>` must be directory and it must exist. Wildcards are not supported.
`copy_directory <dir>... <destination>` Copy directories to `<destination>` directory. If `<destination>` directory does not exist it will be created.
`copy_if_different <file>... <destination>` Copy files to `<destination>` (either file or directory) if they have changed. If multiple files are specified, the `<destination>` must be directory and it must exist.
`echo [<string>...]` Displays arguments as text.
`echo_append [<string>...]` Displays arguments as text but no new line.
`env [--unset=NAME]... [NAME=VALUE]... COMMAND [ARG]...` Run command in a modified environment.
`environment` Display the current environment variables.
`make_directory <dir>...` Create `<dir>` directories. If necessary, create parent directories too. If a directory already exists it will be silently ignored.
`md5sum <file>...`
Create MD5 checksum of files in `md5sum` compatible format:
```
351abe79cd3800b38cdfb25d45015a15 file1.txt
052f86c15bbde68af55c7f7b340ab639 file2.txt
```
`remove [-f] <file>...` Remove the file(s). If any of the listed files already do not exist, the command returns a non-zero exit code, but no message is logged. The `-f` option changes the behavior to return a zero exit code (i.e. success) in such situations instead.
`remove_directory <dir>` Remove a directory and its contents. If a directory does not exist it will be silently ignored.
`rename <oldname> <newname>` Rename a file or directory (on one volume).
`server` Launch [`cmake-server(7)`](cmake-server.7#manual:cmake-server(7) "cmake-server(7)") mode.
`sleep <number>...` Sleep for given number of seconds.
`tar [cxt][vf][zjJ] file.tar [<options>...] [--] [<file>...]`
Create or extract a tar or zip archive. Options are:
`--` Stop interpreting options and treat all remaining arguments as file names even if they start in `-`.
`--files-from=<file>` Read file names from the given file, one per line. Blank lines are ignored. Lines may not start in `-` except for `--add-file=<name>` to add files whose names start in `-`.
`--mtime=<date>` Specify modification time recorded in tarball entries.
`--format=<format>` Specify the format of the archive to be created. Supported formats are: `7zip`, `gnutar`, `pax`, `paxr` (restricted pax, default), and `zip`.
`time <command> [<args>...]` Run command and return elapsed time.
`touch <file>` Touch a file.
`touch_nocreate <file>` Touch a file if it exists but do not create it. If a file does not exist it will be silently ignored. ### UNIX-specific Command-Line Tools
The following `cmake -E` commands are available only on UNIX:
`create_symlink <old> <new>` Create a symbolic link `<new>` naming `<old>`. Note
Path to where `<new>` symbolic link will be created has to exist beforehand.
### Windows-specific Command-Line Tools
The following `cmake -E` commands are available only on Windows:
`delete_regv <key>` Delete Windows registry value.
`env_vs8_wince <sdkname>` Displays a batch file which sets the environment for the provided Windows CE SDK installed in VS2005.
`env_vs9_wince <sdkname>` Displays a batch file which sets the environment for the provided Windows CE SDK installed in VS2008.
`write_regv <key> <value>` Write Windows registry value. Find-Package Tool Mode
----------------------
CMake provides a helper for Makefile-based projects with the signature:
```
cmake --find-package <options>...
```
This runs in a pkg-config like mode.
Search a package using [`find_package()`](../command/find_package#command:find_package "find_package") and print the resulting flags to stdout. This can be used to use cmake instead of pkg-config to find installed libraries in plain Makefile-based projects or in autoconf-based projects (via `share/aclocal/cmake.m4`).
Note
This mode is not well-supported due to some technical limitations. It is kept for compatibility but should not be used in new projects.
See Also
--------
The following resources are available to get help using CMake:
Home Page
<https://cmake.org>
The primary starting point for learning about CMake.
Frequently Asked Questions
<https://cmake.org/Wiki/CMake_FAQ>
A Wiki is provided containing answers to frequently asked questions.
Online Documentation
<https://cmake.org/documentation>
Links to available documentation may be found on this web page.
Mailing List
<https://cmake.org/mailing-lists>
For help and discussion about using cmake, a mailing list is provided at [[email protected]](mailto:cmake%40cmake.org). The list is member-post-only but one may sign up on the CMake web page. Please first read the full documentation at <https://cmake.org> before posting questions to the list.
| programming_docs |
cmake cmake-gui(1) cmake-gui(1)
============
Synopsis
--------
```
cmake-gui [<options>]
cmake-gui [<options>] (<path-to-source> | <path-to-existing-build>)
```
Description
-----------
The “cmake-gui” executable is the CMake GUI. Project configuration settings may be specified interactively. Brief instructions are provided at the bottom of the window when the program is running.
CMake is a cross-platform build system generator. Projects specify their build process with platform-independent CMake listfiles included in each directory of a source tree with the name CMakeLists.txt. Users build a project by using CMake to generate a build system for a native tool on their platform.
Options
-------
`--help,-help,-usage,-h,-H,/?`
Print usage information and exit.
Usage describes the basic command line interface and its options.
`--version,-version,/V [<f>]`
Show program name/version banner and exit.
If a file is specified, the version is written into it. The help is printed to a named <f>ile if given.
`--help-full [<f>]`
Print all help manuals and exit.
All manuals are printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-manual <man> [<f>]`
Print one help manual and exit.
The specified manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-manual-list [<f>]`
List help manuals available and exit.
The list contains all manuals for which help may be obtained by using the `--help-manual` option followed by a manual name. The help is printed to a named <f>ile if given.
`--help-command <cmd> [<f>]`
Print help for one command and exit.
The [`cmake-commands(7)`](cmake-commands.7#manual:cmake-commands(7) "cmake-commands(7)") manual entry for `<cmd>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-command-list [<f>]`
List commands with help available and exit.
The list contains all commands for which help may be obtained by using the `--help-command` option followed by a command name. The help is printed to a named <f>ile if given.
`--help-commands [<f>]`
Print cmake-commands manual and exit.
The [`cmake-commands(7)`](cmake-commands.7#manual:cmake-commands(7) "cmake-commands(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-module <mod> [<f>]`
Print help for one module and exit.
The [`cmake-modules(7)`](cmake-modules.7#manual:cmake-modules(7) "cmake-modules(7)") manual entry for `<mod>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-module-list [<f>]`
List modules with help available and exit.
The list contains all modules for which help may be obtained by using the `--help-module` option followed by a module name. The help is printed to a named <f>ile if given.
`--help-modules [<f>]`
Print cmake-modules manual and exit.
The [`cmake-modules(7)`](cmake-modules.7#manual:cmake-modules(7) "cmake-modules(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-policy <cmp> [<f>]`
Print help for one policy and exit.
The [`cmake-policies(7)`](cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") manual entry for `<cmp>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-policy-list [<f>]`
List policies with help available and exit.
The list contains all policies for which help may be obtained by using the `--help-policy` option followed by a policy name. The help is printed to a named <f>ile if given.
`--help-policies [<f>]`
Print cmake-policies manual and exit.
The [`cmake-policies(7)`](cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-property <prop> [<f>]`
Print help for one property and exit.
The [`cmake-properties(7)`](cmake-properties.7#manual:cmake-properties(7) "cmake-properties(7)") manual entries for `<prop>` are printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-property-list [<f>]`
List properties with help available and exit.
The list contains all properties for which help may be obtained by using the `--help-property` option followed by a property name. The help is printed to a named <f>ile if given.
`--help-properties [<f>]`
Print cmake-properties manual and exit.
The [`cmake-properties(7)`](cmake-properties.7#manual:cmake-properties(7) "cmake-properties(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-variable <var> [<f>]`
Print help for one variable and exit.
The [`cmake-variables(7)`](cmake-variables.7#manual:cmake-variables(7) "cmake-variables(7)") manual entry for `<var>` is printed in a human-readable text format. The help is printed to a named <f>ile if given.
`--help-variable-list [<f>]`
List variables with help available and exit.
The list contains all variables for which help may be obtained by using the `--help-variable` option followed by a variable name. The help is printed to a named <f>ile if given.
`--help-variables [<f>]`
Print cmake-variables manual and exit.
The [`cmake-variables(7)`](cmake-variables.7#manual:cmake-variables(7) "cmake-variables(7)") manual is printed in a human-readable text format. The help is printed to a named <f>ile if given.
See Also
--------
The following resources are available to get help using CMake:
Home Page
<https://cmake.org>
The primary starting point for learning about CMake.
Frequently Asked Questions
<https://cmake.org/Wiki/CMake_FAQ>
A Wiki is provided containing answers to frequently asked questions.
Online Documentation
<https://cmake.org/documentation>
Links to available documentation may be found on this web page.
Mailing List
<https://cmake.org/mailing-lists>
For help and discussion about using cmake, a mailing list is provided at [[email protected]](mailto:cmake%40cmake.org). The list is member-post-only but one may sign up on the CMake web page. Please first read the full documentation at <https://cmake.org> before posting questions to the list.
cmake cmake-server(7) cmake-server(7)
===============
* [Introduction](#introduction)
* [Operation](#operation)
* [Debugging](#debugging)
* [Protocol API](#protocol-api)
+ [General Message Layout](#general-message-layout)
- [Type “reply”](#type-reply)
- [Type “error”](#type-error)
- [Type “progress”](#type-progress)
- [Type “message”](#type-message)
- [Type “signal”](#type-signal)
+ [Specific Signals](#specific-signals)
- [“dirty” Signal](#dirty-signal)
- [“fileChange” Signal](#filechange-signal)
+ [Specific Message Types](#specific-message-types)
- [Type “hello”](#type-hello)
- [Type “handshake”](#type-handshake)
- [Type “globalSettings”](#type-globalsettings)
- [Type “setGlobalSettings”](#type-setglobalsettings)
- [Type “configure”](#type-configure)
- [Type “compute”](#type-compute)
- [Type “codemodel”](#type-codemodel)
- [Type “cmakeInputs”](#type-cmakeinputs)
- [Type “cache”](#type-cache)
- [Type “fileSystemWatchers”](#type-filesystemwatchers)
Introduction
------------
[`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") is capable of providing semantic information about CMake code it executes to generate a buildsystem. If executed with the `-E server` command line options, it starts in a long running mode and allows a client to request the available information via a JSON protocol.
The protocol is designed to be useful to IDEs, refactoring tools, and other tools which have a need to understand the buildsystem in entirety.
A single [`cmake-buildsystem(7)`](cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") may describe buildsystem contents and build properties which differ based on [`generation-time context`](cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") including:
* The Platform (eg, Windows, APPLE, Linux).
* The build configuration (eg, Debug, Release, Coverage).
* The Compiler (eg, MSVC, GCC, Clang) and compiler version.
* The language of the source files compiled.
* Available compile features (eg CXX variadic templates).
* CMake policies.
The protocol aims to provide information to tooling to satisfy several needs:
1. Provide a complete and easily parsed source of all information relevant to the tooling as it relates to the source code. There should be no need for tooling to parse generated buildsystems to access include directories or compile definitions for example.
2. Semantic information about the CMake buildsystem itself.
3. Provide a stable interface for reading the information in the CMake cache.
4. Information for determining when cmake needs to be re-run as a result of file changes.
Operation
---------
Start [`cmake(1)`](cmake.1#manual:cmake(1) "cmake(1)") in the server command mode, supplying the path to the build directory to process:
```
cmake -E server (--debug|--pipe <NAMED_PIPE>)
```
The server will communicate using stdin/stdout (with the `--debug` parameter) or using a named pipe (with the `--pipe <NAMED_PIPE>` parameter).
When connecting to the server (via named pipe or by starting it in `--debug` mode), the server will reply with a hello message:
```
[== "CMake Server" ==[
{"supportedProtocolVersions":[{"major":1,"minor":0}],"type":"hello"}
]== "CMake Server" ==]
```
Messages sent to and from the process are wrapped in magic strings:
```
[== "CMake Server" ==[
{
... some JSON message ...
}
]== "CMake Server" ==]
```
The server is now ready to accept further requests via the named pipe or stdin.
Debugging
---------
CMake server mode can be asked to provide statistics on execution times, etc. or to dump a copy of the response into a file. This is done passing a “debug” JSON object as a child of the request.
The debug object supports the “showStats” key, which takes a boolean and makes the server mode return a “zzzDebug” object with stats as part of its response. “dumpToFile” takes a string value and will cause the cmake server to copy the response into the given filename.
This is a response from the cmake server with “showStats” set to true:
```
[== "CMake Server" ==[
{
"cookie":"",
"errorMessage":"Waiting for type \"handshake\".",
"inReplyTo":"unknown",
"type":"error",
"zzzDebug": {
"dumpFile":"/tmp/error.txt",
"jsonSerialization":0.011016,
"size":111,
"totalTime":0.025995
}
}
]== "CMake Server" ==]
```
The server has made a copy of this response into the file /tmp/error.txt and took 0.011 seconds to turn the JSON response into a string, and it took 0.025 seconds to process the request in total. The reply has a size of 111 bytes.
Protocol API
------------
### General Message Layout
All messages need to have a “type” value, which identifies the type of message that is passed back or forth. E.g. the initial message sent by the server is of type “hello”. Messages without a type will generate an response of type “error”.
All requests sent to the server may contain a “cookie” value. This value will he handed back unchanged in all responses triggered by the request.
All responses will contain a value “inReplyTo”, which may be empty in case of parse errors, but will contain the type of the request message in all other cases.
#### Type “reply”
This type is used by the server to reply to requests.
The message may – depending on the type of the original request – contain values.
Example:
```
[== "CMake Server" ==[
{"cookie":"zimtstern","inReplyTo":"handshake","type":"reply"}
]== "CMake Server" ==]
```
#### Type “error”
This type is used to return an error condition to the client. It will contain an “errorMessage”.
Example:
```
[== "CMake Server" ==[
{"cookie":"","errorMessage":"Protocol version not supported.","inReplyTo":"handshake","type":"error"}
]== "CMake Server" ==]
```
#### Type “progress”
When the server is busy for a long time, it is polite to send back replies of type “progress” to the client. These will contain a “progressMessage” with a string describing the action currently taking place as well as “progressMinimum”, “progressMaximum” and “progressCurrent” with integer values describing the range of progess.
Messages of type “progress” will be followed by more “progress” messages or with a message of type “reply” or “error” that complete the request.
“progress” messages may not be emitted after the “reply” or “error” message for the request that triggered the responses was delivered.
#### Type “message”
A message is triggered when the server processes a request and produces some form of output that should be displayed to the user. A Message has a “message” with the actual text to display as well as a “title” with a suggested dialog box title.
Example:
```
[== "CMake Server" ==[
{"cookie":"","message":"Something happened.","title":"Title Text","inReplyTo":"handshake","type":"message"}
]== "CMake Server" ==]
```
#### Type “signal”
The server can send signals when it detects changes in the system state. Signals are of type “signal”, have an empty “cookie” and “inReplyTo” field and always have a “name” set to show which signal was sent.
### Specific Signals
The cmake server may sent signals with the following names:
#### “dirty” Signal
The “dirty” signal is sent whenever the server determines that the configuration of the project is no longer up-to-date. This happens when any of the files that have an influence on the build system is changed.
The “dirty” signal may look like this:
```
[== "CMake Server" ==[
{
"cookie":"",
"inReplyTo":"",
"name":"dirty",
"type":"signal"}
]== "CMake Server" ==]
```
#### “fileChange” Signal
The “fileChange” signal is sent whenever a watched file is changed. It contains the “path” that has changed and a list of “properties” with the kind of change that was detected. Possible changes are “change” and “rename”.
The “fileChange” signal looks like this:
```
[== "CMake Server" ==[
{
"cookie":"",
"inReplyTo":"",
"name":"fileChange",
"path":"/absolute/CMakeLists.txt",
"properties":["change"],
"type":"signal"}
]== "CMake Server" ==]
```
### Specific Message Types
#### Type “hello”
The initial message send by the cmake server on startup is of type “hello”. This is the only message ever sent by the server that is not of type “reply”, “progress” or “error”.
It will contain “supportedProtocolVersions” with an array of server protocol versions supported by the cmake server. These are JSON objects with “major” and “minor” keys containing non-negative integer values. Some versions may be marked as experimental. These will contain the “isExperimental” key set to true. Enabling these requires a special command line argument when starting the cmake server mode.
Example:
```
[== "CMake Server" ==[
{"supportedProtocolVersions":[{"major":0,"minor":1}],"type":"hello"}
]== "CMake Server" ==]
```
#### Type “handshake”
The first request that the client may send to the server is of type “handshake”.
This request needs to pass one of the “supportedProtocolVersions” of the “hello” type response received earlier back to the server in the “protocolVersion” field.
Each protocol version may request additional attributes to be present.
Protocol version 1.0 requires the following attributes to be set:
* “sourceDirectory” with a path to the sources
* “buildDirectory” with a path to the build directory
* “generator” with the generator name
* “extraGenerator” (optional!) with the extra generator to be used
* “platform” with the generator platform (if supported by the generator)
* “toolset” with the generator toolset (if supported by the generator)
Example:
```
[== "CMake Server" ==[
{"cookie":"zimtstern","type":"handshake","protocolVersion":{"major":0},
"sourceDirectory":"/home/code/cmake", "buildDirectory":"/tmp/testbuild",
"generator":"Ninja"}
]== "CMake Server" ==]
```
which will result in a response type “reply”:
```
[== "CMake Server" ==[
{"cookie":"zimtstern","inReplyTo":"handshake","type":"reply"}
]== "CMake Server" ==]
```
indicating that the server is ready for action.
#### Type “globalSettings”
This request can be sent after the initial handshake. It will return a JSON structure with information on cmake state.
Example:
```
[== "CMake Server" ==[
{"type":"globalSettings"}
]== "CMake Server" ==]
```
which will result in a response type “reply”:
```
[== "CMake Server" ==[
{
"buildDirectory": "/tmp/test-build",
"capabilities": {
"generators": [
{
"extraGenerators": [],
"name": "Watcom WMake",
"platformSupport": false,
"toolsetSupport": false
},
<...>
],
"serverMode": false,
"version": {
"isDirty": false,
"major": 3,
"minor": 6,
"patch": 20160830,
"string": "3.6.20160830-gd6abad",
"suffix": "gd6abad"
}
},
"checkSystemVars": false,
"cookie": "",
"extraGenerator": "",
"generator": "Ninja",
"debugOutput": false,
"inReplyTo": "globalSettings",
"sourceDirectory": "/home/code/cmake",
"trace": false,
"traceExpand": false,
"type": "reply",
"warnUninitialized": false,
"warnUnused": false,
"warnUnusedCli": true
}
]== "CMake Server" ==]
```
#### Type “setGlobalSettings”
This request can be sent to change the global settings attributes. Unknown attributes are going to be ignored. Read-only attributes reported by “globalSettings” are all capabilities, buildDirectory, generator, extraGenerator and sourceDirectory. Any attempt to set these will be ignored, too.
All other settings will be changed.
The server will respond with an empty reply message or an error.
Example:
```
[== "CMake Server" ==[
{"type":"setGlobalSettings","debugOutput":true}
]== "CMake Server" ==]
```
CMake will reply to this with:
```
[== "CMake Server" ==[
{"inReplyTo":"setGlobalSettings","type":"reply"}
]== "CMake Server" ==]
```
#### Type “configure”
This request will configure a project for build.
To configure a build directory already containing cmake files, it is enough to set “buildDirectory” via “setGlobalSettings”. To create a fresh build directory you also need to set “currentGenerator” and “sourceDirectory” via “setGlobalSettings” in addition to “buildDirectory”.
You may a list of strings to “configure” via the “cacheArguments” key. These strings will be interpreted similar to command line arguments related to cache handling that are passed to the cmake command line client.
Example:
```
[== "CMake Server" ==[
{"type":"configure", "cacheArguments":["-Dsomething=else"]}
]== "CMake Server" ==]
```
CMake will reply like this (after reporting progress for some time):
```
[== "CMake Server" ==[
{"cookie":"","inReplyTo":"configure","type":"reply"}
]== "CMake Server" ==]
```
#### Type “compute”
This request will generate build system files in the build directory and is only available after a project was successfully “configure”d.
Example:
```
[== "CMake Server" ==[
{"type":"compute"}
]== "CMake Server" ==]
```
CMake will reply (after reporting progress information):
```
[== "CMake Server" ==[
{"cookie":"","inReplyTo":"compute","type":"reply"}
]== "CMake Server" ==]
```
#### Type “codemodel”
The “codemodel” request can be used after a project was “compute”d successfully.
It will list the complete project structure as it is known to cmake.
The reply will contain a key “configurations”, which will contain a list of configuration objects. Configuration objects are used to destinquish between different configurations the build directory might have enabled. While most generators only support one configuration, others might support several.
Each configuration object can have the following keys:
“name” contains the name of the configuration. The name may be empty. “projects” contains a list of project objects, one for each build project. Project objects define one (sub-)project defined in the cmake build system.
Each project object can have the following keys:
“name” contains the (sub-)projects name. “sourceDirectory” contains the current source directory “buildDirectory” contains the current build directory. “targets” contains a list of build system target objects. Target objects define individual build targets for a certain configuration.
Each target object can have the following keys:
“name” contains the name of the target. “type” defines the type of build of the target. Possible values are “STATIC\_LIBRARY”, “MODULE\_LIBRARY”, “SHARED\_LIBRARY”, “OBJECT\_LIBRARY”, “EXECUTABLE”, “UTILITY” and “INTERFACE\_LIBRARY”. “fullName” contains the full name of the build result (incl. extensions, etc.). “sourceDirectory” contains the current source directory. “buildDirectory” contains the current build directory. “artifacts” with a list of build artifacts. The list is sorted with the most important artifacts first (e.g. a .DLL file is listed before a .PDB file on windows). “linkerLanguage” contains the language of the linker used to produce the artifact. “linkLibraries” with a list of libraries to link to. This value is encoded in the system’s native shell format. “linkFlags” with a list of flags to pass to the linker. This value is encoded in the system’s native shell format. “linkLanguageFlags” with the flags for a compiler using the linkerLanguage. This value is encoded in the system’s native shell format. “frameworkPath” with the framework path (on Apple computers). This value is encoded in the system’s native shell format. “linkPath” with the link path. This value is encoded in the system’s native shell format. “sysroot” with the sysroot path. “fileGroups” contains the source files making up the target. FileGroups are used to group sources using similar settings together.
Each fileGroup object may contain the following keys:
“language” contains the programming language used by all files in the group. “compileFlags” with a string containing all the flags passed to the compiler when building any of the files in this group. This value is encoded in the system’s native shell format. “includePath” with a list of include paths. Each include path is an object containing a “path” with the actual include path and “isSystem” with a bool value informing whether this is a normal include or a system include. This value is encoded in the system’s native shell format. “defines” with a list of defines in the form “SOMEVALUE” or “SOMEVALUE=42”. This value is encoded in the system’s native shell format. “sources” with a list of source files. All file paths in the fileGroup are either absolute or relative to the sourceDirectory of the target.
Example:
```
[== "CMake Server" ==[
{"type":"codemodel"}
]== "CMake Server" ==]
```
CMake will reply:
```
[== "CMake Server" ==[
{
"configurations": [
{
"name": "",
"projects": [
{
"buildDirectory": "/tmp/build/Source/CursesDialog/form",
"name": "CMAKE_FORM",
"sourceDirectory": "/home/code/src/cmake/Source/CursesDialog/form",
"targets": [
{
"artifacts": [ "/tmp/build/Source/CursesDialog/form/libcmForm.a" ],
"buildDirectory": "/tmp/build/Source/CursesDialog/form",
"fileGroups": [
{
"compileFlags": " -std=gnu11",
"defines": [ "CURL_STATICLIB", "LIBARCHIVE_STATIC" ],
"includePath": [ { "path": "/tmp/build/Utilities" }, <...> ],
"isGenerated": false,
"language": "C",
"sources": [ "fld_arg.c", <...> ]
}
],
"fullName": "libcmForm.a",
"linkerLanguage": "C",
"name": "cmForm",
"sourceDirectory": "/home/code/src/cmake/Source/CursesDialog/form",
"type": "STATIC_LIBRARY"
}
]
},
<...>
]
}
],
"cookie": "",
"inReplyTo": "codemodel",
"type": "reply"
}
]== "CMake Server" ==]
```
#### Type “cmakeInputs”
The “cmakeInputs” requests will report files used by CMake as part of the build system itself.
This request is only available after a project was successfully “configure”d.
Example:
```
[== "CMake Server" ==[
{"type":"cmakeInputs"}
]== "CMake Server" ==]
```
CMake will reply with the following information:
```
[== "CMake Server" ==[
{"buildFiles":
[
{"isCMake":true,"isTemporary":false,"sources":["/usr/lib/cmake/...", ... ]},
{"isCMake":false,"isTemporary":false,"sources":["CMakeLists.txt", ...]},
{"isCMake":false,"isTemporary":true,"sources":["/tmp/build/CMakeFiles/...", ...]}
],
"cmakeRootDirectory":"/usr/lib/cmake",
"sourceDirectory":"/home/code/src/cmake",
"cookie":"",
"inReplyTo":"cmakeInputs",
"type":"reply"
}
]== "CMake Server" ==]
```
All file names are either relative to the top level source directory or absolute.
The list of files which “isCMake” set to true are part of the cmake installation.
The list of files witch “isTemporary” set to true are part of the build directory and will not survive the build directory getting cleaned out.
#### Type “cache”
The “cache” request can be used once a project is configured and will list the cached configuration values.
Example:
```
[== "CMake Server" ==[
{"type":"cache"}
]== "CMake Server" ==]
```
CMake will respond with the following output:
```
[== "CMake Server" ==[
{
"cookie":"","inReplyTo":"cache","type":"reply",
"cache":
[
{
"key":"SOMEVALUE",
"properties":
{
"ADVANCED":"1",
"HELPSTRING":"This is not helpful"
}
"type":"STRING",
"value":"TEST"}
]
}
]== "CMake Server" ==]
```
The output can be limited to a list of keys by passing an array of key names to the “keys” optional field of the “cache” request.
#### Type “fileSystemWatchers”
The server can watch the filesystem for changes. The “fileSystemWatchers” command will report on the files and directories watched.
Example:
```
[== "CMake Server" ==[
{"type":"fileSystemWatchers"}
]== "CMake Server" ==]
```
CMake will respond with the following output:
```
[== "CMake Server" ==[
{
"cookie":"","inReplyTo":"fileSystemWatchers","type":"reply",
"watchedFiles": [ "/absolute/path" ],
"watchedDirectories": [ "/absolute" ]
}
]== "CMake Server" ==]
```
| programming_docs |
cmake IMPLICIT_DEPENDS_INCLUDE_TRANSFORM IMPLICIT\_DEPENDS\_INCLUDE\_TRANSFORM
=====================================
Specify #include line transforms for dependencies in a directory.
This property specifies rules to transform macro-like #include lines during implicit dependency scanning of C and C++ source files. The list of rules must be semicolon-separated with each entry of the form “A\_MACRO(%)=value-with-%” (the % must be literal). During dependency scanning occurrences of A\_MACRO(…) on #include lines will be replaced by the value given with the macro argument substituted for ‘%’. For example, the entry
```
MYDIR(%)=<mydir/%>
```
will convert lines of the form
```
#include MYDIR(myheader.h)
```
to
```
#include <mydir/myheader.h>
```
allowing the dependency to be followed.
This property applies to sources in all targets within a directory. The property value is initialized in each directory by its value in the directory’s parent.
cmake VS_GLOBAL_SECTION_POST_<section> VS\_GLOBAL\_SECTION\_POST\_<section>
====================================
Specify a postSolution global section in Visual Studio.
Setting a property like this generates an entry of the following form in the solution file:
```
GlobalSection(<section>) = postSolution
<contents based on property value>
EndGlobalSection
```
The property must be set to a semicolon-separated list of key=value pairs. Each such pair will be transformed into an entry in the solution global section. Whitespace around key and value is ignored. List elements which do not contain an equal sign are skipped.
This property only works for Visual Studio 8 and above; it is ignored on other generators. The property only applies when set on a directory whose CMakeLists.txt contains a project() command.
Note that CMake generates postSolution sections ExtensibilityGlobals and ExtensibilityAddIns by default. If you set the corresponding property, it will override the default section. For example, setting VS\_GLOBAL\_SECTION\_POST\_ExtensibilityGlobals will override the default contents of the ExtensibilityGlobals section, while keeping ExtensibilityAddIns on its default. However, CMake will always add a `SolutionGuid` to the `ExtensibilityGlobals` section if it is not specified explicitly.
cmake VS_STARTUP_PROJECT VS\_STARTUP\_PROJECT
====================
Specify the default startup project in a Visual Studio solution.
The [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators) create a `.sln` file for each directory whose `CMakeLists.txt` file calls the [`project()`](../command/project#command:project "project") command. Set this property in the same directory as a [`project()`](../command/project#command:project "project") command call (e.g. in the top-level `CMakeLists.txt` file) to specify the default startup project for the correpsonding solution file.
The property must be set to the name of an existing target. This will cause that project to be listed first in the generated solution file causing Visual Studio to make it the startup project if the solution has never been opened before.
If this property is not specified, then the `ALL_BUILD` project will be the default.
cmake BUILDSYSTEM_TARGETS BUILDSYSTEM\_TARGETS
====================
This read-only directory property contains a [;-list](../manual/cmake-language.7#cmake-language-lists) of buildsystem targets added in the directory by calls to the [`add_library()`](../command/add_library#command:add_library "add_library"), [`add_executable()`](../command/add_executable#command:add_executable "add_executable"), and [`add_custom_target()`](../command/add_custom_target#command:add_custom_target "add_custom_target") commands. The list does not include any [Imported Targets](../manual/cmake-buildsystem.7#imported-targets) or [Alias Targets](../manual/cmake-buildsystem.7#alias-targets), but does include [Interface Libraries](../manual/cmake-buildsystem.7#interface-libraries). Each entry in the list is the logical name of a target, suitable to pass to the [`get_property()`](../command/get_property#command:get_property "get_property") command `TARGET` option.
cmake ADDITIONAL_MAKE_CLEAN_FILES ADDITIONAL\_MAKE\_CLEAN\_FILES
==============================
Additional files to clean during the make clean stage.
A list of files that will be cleaned as a part of the “make clean” stage.
cmake INTERPROCEDURAL_OPTIMIZATION INTERPROCEDURAL\_OPTIMIZATION
=============================
Enable interprocedural optimization for targets in a directory.
If set to true, enables interprocedural optimizations if they are known to be supported by the compiler.
cmake LISTFILE_STACK LISTFILE\_STACK
===============
The current stack of listfiles being processed.
This property is mainly useful when trying to debug errors in your CMake scripts. It returns a list of what list files are currently being processed, in order. So if one listfile does an [`include()`](../command/include#command:include "include") command then that is effectively pushing the included listfile onto the stack.
cmake EXCLUDE_FROM_ALL EXCLUDE\_FROM\_ALL
==================
Exclude the directory from the all target of its parent.
A property on a directory that indicates if its targets are excluded from the default build target. If it is not, then with a Makefile for example typing make will cause the targets to be built. The same concept applies to the default build of other generators.
cmake LINK_DIRECTORIES LINK\_DIRECTORIES
=================
List of linker search directories.
This read-only property specifies the list of directories given so far to the link\_directories command. It is intended for debugging purposes.
cmake COMPILE_DEFINITIONS COMPILE\_DEFINITIONS
====================
Preprocessor definitions for compiling a directory’s sources.
This property specifies the list of options given so far to the [`add_definitions()`](../command/add_definitions#command:add_definitions "add_definitions") command.
The `COMPILE_DEFINITIONS` property may be set to a semicolon-separated list of preprocessor definitions using the syntax `VAR` or `VAR=value`. Function-style definitions are not supported. CMake will automatically escape the value correctly for the native build system (note that CMake language syntax may require escapes to specify some values).
This property will be initialized in each directory by its value in the directory’s parent.
CMake will automatically drop some definitions that are not supported by the native build tool.
Disclaimer: Most native build tools have poor support for escaping certain values. CMake has work-arounds for many cases but some values may just not be possible to pass correctly. If a value does not seem to be escaped correctly, do not attempt to work-around the problem by adding escape sequences to the value. Your work-around may break in a future version of CMake that has improved escape support. Instead consider defining the macro in a (configured) header file. Then report the limitation. Known limitations include:
```
# - broken almost everywhere
; - broken in VS IDE 7.0 and Borland Makefiles
, - broken in VS IDE
% - broken in some cases in NMake
& | - broken in some cases on MinGW
^ < > \" - broken in most Make tools on Windows
```
CMake does not reject these values outright because they do work in some cases. Use with caution.
Contents of `COMPILE_DEFINITIONS` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
The corresponding [`COMPILE_DEFINITIONS_<CONFIG>`](# "COMPILE_DEFINITIONS_<CONFIG>") property may be set to specify per-configuration definitions. Generator expressions should be preferred instead of setting the alternative property.
cmake CACHE_VARIABLES CACHE\_VARIABLES
================
List of cache variables available in the current directory.
This read-only property specifies the list of CMake cache variables currently defined. It is intended for debugging purposes.
cmake VARIABLES VARIABLES
=========
List of variables defined in the current directory.
This read-only property specifies the list of CMake variables currently defined. It is intended for debugging purposes.
cmake COMPILE_DEFINITIONS_<CONFIG> COMPILE\_DEFINITIONS\_<CONFIG>
==============================
Ignored. See CMake Policy [`CMP0043`](../policy/cmp0043#policy:CMP0043 "CMP0043").
Per-configuration preprocessor definitions in a directory.
This is the configuration-specific version of [`COMPILE_DEFINITIONS`](compile_definitions#prop_dir:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") where `<CONFIG>` is an upper-case name (ex. `COMPILE_DEFINITIONS_DEBUG`).
This property will be initialized in each directory by its value in the directory’s parent.
Contents of `COMPILE_DEFINITIONS_<CONFIG>` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
Generator expressions should be preferred instead of setting this property.
cmake DEFINITIONS DEFINITIONS
===========
For CMake 2.4 compatibility only. Use [`COMPILE_DEFINITIONS`](compile_definitions#prop_dir:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") instead.
This read-only property specifies the list of flags given so far to the [`add_definitions()`](../command/add_definitions#command:add_definitions "add_definitions") command. It is intended for debugging purposes. Use the [`COMPILE_DEFINITIONS`](compile_definitions#prop_dir:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") directory property instead.
This built-in read-only property does not exist if policy [`CMP0059`](../policy/cmp0059#policy:CMP0059 "CMP0059") is set to `NEW`.
cmake SOURCE_DIR SOURCE\_DIR
===========
This read-only directory property reports absolute path to the source directory on which it is read.
cmake CMAKE_CONFIGURE_DEPENDS CMAKE\_CONFIGURE\_DEPENDS
=========================
Tell CMake about additional input files to the configuration process. If any named file is modified the build system will re-run CMake to re-configure the file and generate the build system again.
Specify files as a semicolon-separated list of paths. Relative paths are interpreted as relative to the current source directory.
cmake MACROS MACROS
======
List of macro commands available in the current directory.
This read-only property specifies the list of CMake macros currently defined. It is intended for debugging purposes. See the macro command.
cmake RULE_LAUNCH_COMPILE RULE\_LAUNCH\_COMPILE
=====================
Specify a launcher for compile rules.
See the global property of the same name for details. This overrides the global property for a directory.
cmake TEST_INCLUDE_FILE TEST\_INCLUDE\_FILE
===================
A cmake file that will be included when ctest is run.
If you specify TEST\_INCLUDE\_FILE, that file will be included and processed when ctest is run on the directory.
cmake INCLUDE_REGULAR_EXPRESSION INCLUDE\_REGULAR\_EXPRESSION
============================
Include file scanning regular expression.
This property specifies the regular expression used during dependency scanning to match include files that should be followed. See the [`include_regular_expression()`](../command/include_regular_expression#command:include_regular_expression "include_regular_expression") command for a high-level interface to set this property.
cmake INCLUDE_DIRECTORIES INCLUDE\_DIRECTORIES
====================
List of preprocessor include file search directories.
This property specifies the list of directories given so far to the [`include_directories()`](../command/include_directories#command:include_directories "include_directories") command.
This property is used to populate the [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES") target property, which is used by the generators to set the include directories for the compiler.
In addition to accepting values from that command, values may be set directly on any directory using the [`set_property()`](../command/set_property#command:set_property "set_property") command. A directory gets its initial value from its parent directory if it has one. The initial value of the [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES") target property comes from the value of this property. Both directory and target property values are adjusted by calls to the [`include_directories()`](../command/include_directories#command:include_directories "include_directories") command.
The target property values are used by the generators to set the include paths for the compiler.
Contents of `INCLUDE_DIRECTORIES` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake RULE_LAUNCH_LINK RULE\_LAUNCH\_LINK
==================
Specify a launcher for link rules.
See the global property of the same name for details. This overrides the global property for a directory.
cmake BINARY_DIR BINARY\_DIR
===========
This read-only directory property reports absolute path to the binary directory corresponding to the source on which it is read.
cmake CLEAN_NO_CUSTOM CLEAN\_NO\_CUSTOM
=================
Set to true to tell [Makefile Generators](../manual/cmake-generators.7#makefile-generators) not to remove the outputs of custom commands for this directory during the `make clean` operation. This is ignored on other generators because it is not possible to implement.
cmake PARENT_DIRECTORY PARENT\_DIRECTORY
=================
Source directory that added current subdirectory.
This read-only property specifies the source directory that added the current source directory as a subdirectory of the build. In the top-level directory the value is the empty-string.
cmake SUBDIRECTORIES SUBDIRECTORIES
==============
This read-only directory property contains a [;-list](../manual/cmake-language.7#cmake-language-lists) of subdirectories processed so far by the [`add_subdirectory()`](../command/add_subdirectory#command:add_subdirectory "add_subdirectory") or [`subdirs()`](../command/subdirs#command:subdirs "subdirs") commands. Each entry is the absolute path to the source directory (containing the `CMakeLists.txt` file). This is suitable to pass to the [`get_property()`](../command/get_property#command:get_property "get_property") command `DIRECTORY` option.
Note
The [`subdirs()`](../command/subdirs#command:subdirs "subdirs") command does not process its arguments until after the calling directory is fully processed. Therefore looking up this property in the current directory will not see them.
cmake COMPILE_OPTIONS COMPILE\_OPTIONS
================
List of options to pass to the compiler.
This property holds a [;-list](../manual/cmake-language.7#cmake-language-lists) of options given so far to the [`add_compile_options()`](../command/add_compile_options#command:add_compile_options "add_compile_options") command.
This property is used to initialize the [`COMPILE_OPTIONS`](../prop_tgt/compile_options#prop_tgt:COMPILE_OPTIONS "COMPILE_OPTIONS") target property when a target is created, which is used by the generators to set the options for the compiler.
Contents of `COMPILE_OPTIONS` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake INTERPROCEDURAL_OPTIMIZATION_<CONFIG> INTERPROCEDURAL\_OPTIMIZATION\_<CONFIG>
=======================================
Per-configuration interprocedural optimization for a directory.
This is a per-configuration version of INTERPROCEDURAL\_OPTIMIZATION. If set, this property overrides the generic property for the named configuration.
cmake VS_GLOBAL_SECTION_PRE_<section> VS\_GLOBAL\_SECTION\_PRE\_<section>
===================================
Specify a preSolution global section in Visual Studio.
Setting a property like this generates an entry of the following form in the solution file:
```
GlobalSection(<section>) = preSolution
<contents based on property value>
EndGlobalSection
```
The property must be set to a semicolon-separated list of key=value pairs. Each such pair will be transformed into an entry in the solution global section. Whitespace around key and value is ignored. List elements which do not contain an equal sign are skipped.
This property only works for Visual Studio 8 and above; it is ignored on other generators. The property only applies when set on a directory whose CMakeLists.txt contains a project() command.
cmake RULE_LAUNCH_CUSTOM RULE\_LAUNCH\_CUSTOM
====================
Specify a launcher for custom rules.
See the global property of the same name for details. This overrides the global property for a directory.
cmake source_group source\_group
=============
Define a grouping for source files in IDE project generation. There are two different signatures to create source groups.
```
source_group(<name> [FILES <src>...] [REGULAR_EXPRESSION <regex>])
source_group(TREE <root> [PREFIX <prefix>] [FILES <src>...])
```
Defines a group into which sources will be placed in project files. This is intended to set up file tabs in Visual Studio. The options are:
`TREE` CMake will automatically detect, from `<src>` files paths, source groups it needs to create, to keep structure of source groups analogically to the actual files and directories structure in the project. Paths of `<src>` files will be cut to be relative to `<root>`.
`PREFIX` Source group and files located directly in `<root>` path, will be placed in `<prefix>` source groups.
`FILES` Any source file specified explicitly will be placed in group `<name>`. Relative paths are interpreted with respect to the current source directory.
`REGULAR_EXPRESSION` Any source file whose name matches the regular expression will be placed in group `<name>`. If a source file matches multiple groups, the *last* group that explicitly lists the file with `FILES` will be favored, if any. If no group explicitly lists the file, the *last* group whose regular expression matches the file will be favored.
The `<name>` of the group and `<prefix>` argument may contain backslashes to specify subgroups:
```
source_group(outer\\inner ...)
source_group(TREE <root> PREFIX sources\\inc ...)
```
For backwards compatibility, the short-hand signature
```
source_group(<name> <regex>)
```
is equivalent to
```
source_group(<name> REGULAR_EXPRESSION <regex>)
```
cmake message message
=======
Display a message to the user.
```
message([<mode>] "message to display" ...)
```
The optional `<mode>` keyword determines the type of message:
```
(none) = Important information
STATUS = Incidental information
WARNING = CMake Warning, continue processing
AUTHOR_WARNING = CMake Warning (dev), continue processing
SEND_ERROR = CMake Error, continue processing,
but skip generation
FATAL_ERROR = CMake Error, stop processing and generation
DEPRECATION = CMake Deprecation Error or Warning if variable
CMAKE_ERROR_DEPRECATED or CMAKE_WARN_DEPRECATED
is enabled, respectively, else no message.
```
The CMake command-line tool displays STATUS messages on stdout and all other message types on stderr. The CMake GUI displays all messages in its log area. The interactive dialogs (ccmake and CMakeSetup) show STATUS messages one at a time on a status line and other messages in interactive pop-up boxes.
CMake Warning and Error message text displays using a simple markup language. Non-indented text is formatted in line-wrapped paragraphs delimited by newlines. Indented text is considered pre-formatted.
| programming_docs |
cmake load_cache load\_cache
===========
Load in the values from another project’s CMake cache.
```
load_cache(pathToCacheFile READ_WITH_PREFIX
prefix entry1...)
```
Read the cache and store the requested entries in variables with their name prefixed with the given prefix. This only reads the values, and does not create entries in the local project’s cache.
```
load_cache(pathToCacheFile [EXCLUDE entry1...]
[INCLUDE_INTERNALS entry1...])
```
Load in the values from another cache and store them in the local project’s cache as internal entries. This is useful for a project that depends on another project built in a different tree. `EXCLUDE` option can be used to provide a list of entries to be excluded. `INCLUDE_INTERNALS` can be used to provide a list of internal entries to be included. Normally, no internal entries are brought in. Use of this form of the command is strongly discouraged, but it is provided for backward compatibility.
cmake install install
=======
* [Introduction](#introduction)
* [Installing Targets](#installing-targets)
* [Installing Files](#installing-files)
* [Installing Directories](#installing-directories)
* [Custom Installation Logic](#custom-installation-logic)
* [Installing Exports](#installing-exports)
Specify rules to run at install time.
Introduction
------------
This command generates installation rules for a project. Rules specified by calls to this command within a source directory are executed in order during installation. The order across directories is not defined.
There are multiple signatures for this command. Some of them define installation options for files and targets. Options common to multiple signatures are covered here but they are valid only for signatures that specify them. The common options are:
`DESTINATION` Specify the directory on disk to which a file will be installed. If a full path (with a leading slash or drive letter) is given it is used directly. If a relative path is given it is interpreted relative to the value of the [`CMAKE_INSTALL_PREFIX`](../variable/cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") variable. The prefix can be relocated at install time using the `DESTDIR` mechanism explained in the [`CMAKE_INSTALL_PREFIX`](../variable/cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX") variable documentation.
`PERMISSIONS` Specify permissions for installed files. Valid permissions are `OWNER_READ`, `OWNER_WRITE`, `OWNER_EXECUTE`, `GROUP_READ`, `GROUP_WRITE`, `GROUP_EXECUTE`, `WORLD_READ`, `WORLD_WRITE`, `WORLD_EXECUTE`, `SETUID`, and `SETGID`. Permissions that do not make sense on certain platforms are ignored on those platforms.
`CONFIGURATIONS` Specify a list of build configurations for which the install rule applies (Debug, Release, etc.).
`COMPONENT` Specify an installation component name with which the install rule is associated, such as “runtime” or “development”. During component-specific installation only install rules associated with the given component name will be executed. During a full installation all components are installed unless marked with `EXCLUDE_FROM_ALL`. If `COMPONENT` is not provided a default component “Unspecified” is created. The default component name may be controlled with the [`CMAKE_INSTALL_DEFAULT_COMPONENT_NAME`](../variable/cmake_install_default_component_name#variable:CMAKE_INSTALL_DEFAULT_COMPONENT_NAME "CMAKE_INSTALL_DEFAULT_COMPONENT_NAME") variable.
`EXCLUDE_FROM_ALL` Specify that the file is excluded from a full installation and only installed as part of a component-specific installation
`RENAME` Specify a name for an installed file that may be different from the original file. Renaming is allowed only when a single file is installed by the command.
`OPTIONAL` Specify that it is not an error if the file to be installed does not exist. Command signatures that install files may print messages during installation. Use the [`CMAKE_INSTALL_MESSAGE`](../variable/cmake_install_message#variable:CMAKE_INSTALL_MESSAGE "CMAKE_INSTALL_MESSAGE") variable to control which messages are printed.
Installing Targets
------------------
```
install(TARGETS targets... [EXPORT <export-name>]
[[ARCHIVE|LIBRARY|RUNTIME|OBJECTS|FRAMEWORK|BUNDLE|
PRIVATE_HEADER|PUBLIC_HEADER|RESOURCE]
[DESTINATION <dir>]
[PERMISSIONS permissions...]
[CONFIGURATIONS [Debug|Release|...]]
[COMPONENT <component>]
[OPTIONAL] [EXCLUDE_FROM_ALL]
[NAMELINK_ONLY|NAMELINK_SKIP]
] [...]
[INCLUDES DESTINATION [<dir> ...]]
)
```
The `TARGETS` form specifies rules for installing targets from a project. There are six kinds of target files that may be installed: `ARCHIVE`, `LIBRARY`, `RUNTIME`, `OBJECTS`, `FRAMEWORK`, and `BUNDLE`. Executables are treated as `RUNTIME` targets, except that those marked with the `MACOSX_BUNDLE` property are treated as `BUNDLE` targets on OS X. Static libraries are treated as `ARCHIVE` targets, except that those marked with the `FRAMEWORK` property are treated as `FRAMEWORK` targets on OS X. Module libraries are always treated as `LIBRARY` targets. For non-DLL platforms shared libraries are treated as `LIBRARY` targets, except that those marked with the `FRAMEWORK` property are treated as `FRAMEWORK` targets on OS X. For DLL platforms the DLL part of a shared library is treated as a `RUNTIME` target and the corresponding import library is treated as an `ARCHIVE` target. All Windows-based systems including Cygwin are DLL platforms. Object libraries are always treated as `OBJECTS` targets. The `ARCHIVE`, `LIBRARY`, `RUNTIME`, `OBJECTS`, and `FRAMEWORK` arguments change the type of target to which the subsequent properties apply. If none is given the installation properties apply to all target types. If only one is given then only targets of that type will be installed (which can be used to install just a DLL or just an import library).
The `PRIVATE_HEADER`, `PUBLIC_HEADER`, and `RESOURCE` arguments cause subsequent properties to be applied to installing a `FRAMEWORK` shared library target’s associated files on non-Apple platforms. Rules defined by these arguments are ignored on Apple platforms because the associated files are installed into the appropriate locations inside the framework folder. See documentation of the [`PRIVATE_HEADER`](../prop_tgt/private_header#prop_tgt:PRIVATE_HEADER "PRIVATE_HEADER"), [`PUBLIC_HEADER`](../prop_tgt/public_header#prop_tgt:PUBLIC_HEADER "PUBLIC_HEADER"), and [`RESOURCE`](../prop_tgt/resource#prop_tgt:RESOURCE "RESOURCE") target properties for details.
Either `NAMELINK_ONLY` or `NAMELINK_SKIP` may be specified as a `LIBRARY` option. On some platforms a versioned shared library has a symbolic link such as:
```
lib<name>.so -> lib<name>.so.1
```
where `lib<name>.so.1` is the soname of the library and `lib<name>.so` is a “namelink” allowing linkers to find the library when given `-l<name>`. The `NAMELINK_ONLY` option causes installation of only the namelink when a library target is installed. The `NAMELINK_SKIP` option causes installation of library files other than the namelink when a library target is installed. When neither option is given both portions are installed. On platforms where versioned shared libraries do not have namelinks or when a library is not versioned the `NAMELINK_SKIP` option installs the library and the `NAMELINK_ONLY` option installs nothing. See the [`VERSION`](../prop_tgt/version#prop_tgt:VERSION "VERSION") and [`SOVERSION`](../prop_tgt/soversion#prop_tgt:SOVERSION "SOVERSION") target properties for details on creating versioned shared libraries.
The `INCLUDES DESTINATION` specifies a list of directories which will be added to the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") target property of the `<targets>` when exported by the [`install(EXPORT)`](#command:install "install") command. If a relative path is specified, it is treated as relative to the `$<INSTALL_PREFIX>`. This is independent of the rest of the argument groups and does not actually install anything.
One or more groups of properties may be specified in a single call to the `TARGETS` form of this command. A target may be installed more than once to different locations. Consider hypothetical targets `myExe`, `mySharedLib`, and `myStaticLib`. The code:
```
install(TARGETS myExe mySharedLib myStaticLib
RUNTIME DESTINATION bin
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib/static)
install(TARGETS mySharedLib DESTINATION /some/full/path)
```
will install `myExe` to `<prefix>/bin` and `myStaticLib` to `<prefix>/lib/static`. On non-DLL platforms `mySharedLib` will be installed to `<prefix>/lib` and `/some/full/path`. On DLL platforms the `mySharedLib` DLL will be installed to `<prefix>/bin` and `/some/full/path` and its import library will be installed to `<prefix>/lib/static` and `/some/full/path`.
The `EXPORT` option associates the installed target files with an export called `<export-name>`. It must appear before any `RUNTIME`, `LIBRARY`, `ARCHIVE`, or `OBJECTS` options. To actually install the export file itself, call `install(EXPORT)`, documented below.
Installing a target with the [`EXCLUDE_FROM_ALL`](../prop_tgt/exclude_from_all#prop_tgt:EXCLUDE_FROM_ALL "EXCLUDE_FROM_ALL") target property set to `TRUE` has undefined behavior.
The install destination given to the target install `DESTINATION` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions.
Installing Files
----------------
```
install(<FILES|PROGRAMS> files... DESTINATION <dir>
[PERMISSIONS permissions...]
[CONFIGURATIONS [Debug|Release|...]]
[COMPONENT <component>]
[RENAME <name>] [OPTIONAL] [EXCLUDE_FROM_ALL])
```
The `FILES` form specifies rules for installing files for a project. File names given as relative paths are interpreted with respect to the current source directory. Files installed by this form are by default given permissions `OWNER_WRITE`, `OWNER_READ`, `GROUP_READ`, and `WORLD_READ` if no `PERMISSIONS` argument is given.
The `PROGRAMS` form is identical to the `FILES` form except that the default permissions for the installed file also include `OWNER_EXECUTE`, `GROUP_EXECUTE`, and `WORLD_EXECUTE`. This form is intended to install programs that are not targets, such as shell scripts. Use the `TARGETS` form to install targets built within the project.
The list of `files...` given to `FILES` or `PROGRAMS` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. However, if any item begins in a generator expression it must evaluate to a full path.
The install destination given to the files install `DESTINATION` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions.
Installing Directories
----------------------
```
install(DIRECTORY dirs... DESTINATION <dir>
[FILE_PERMISSIONS permissions...]
[DIRECTORY_PERMISSIONS permissions...]
[USE_SOURCE_PERMISSIONS] [OPTIONAL] [MESSAGE_NEVER]
[CONFIGURATIONS [Debug|Release|...]]
[COMPONENT <component>] [EXCLUDE_FROM_ALL]
[FILES_MATCHING]
[[PATTERN <pattern> | REGEX <regex>]
[EXCLUDE] [PERMISSIONS permissions...]] [...])
```
The `DIRECTORY` form installs contents of one or more directories to a given destination. The directory structure is copied verbatim to the destination. The last component of each directory name is appended to the destination directory but a trailing slash may be used to avoid this because it leaves the last component empty. Directory names given as relative paths are interpreted with respect to the current source directory. If no input directory names are given the destination directory will be created but nothing will be installed into it. The `FILE_PERMISSIONS` and `DIRECTORY_PERMISSIONS` options specify permissions given to files and directories in the destination. If `USE_SOURCE_PERMISSIONS` is specified and `FILE_PERMISSIONS` is not, file permissions will be copied from the source directory structure. If no permissions are specified files will be given the default permissions specified in the `FILES` form of the command, and the directories will be given the default permissions specified in the `PROGRAMS` form of the command.
The `MESSAGE_NEVER` option disables file installation status output.
Installation of directories may be controlled with fine granularity using the `PATTERN` or `REGEX` options. These “match” options specify a globbing pattern or regular expression to match directories or files encountered within input directories. They may be used to apply certain options (see below) to a subset of the files and directories encountered. The full path to each input file or directory (with forward slashes) is matched against the expression. A `PATTERN` will match only complete file names: the portion of the full path matching the pattern must occur at the end of the file name and be preceded by a slash. A `REGEX` will match any portion of the full path but it may use `/` and `$` to simulate the `PATTERN` behavior. By default all files and directories are installed whether or not they are matched. The `FILES_MATCHING` option may be given before the first match option to disable installation of files (but not directories) not matched by any expression. For example, the code
```
install(DIRECTORY src/ DESTINATION include/myproj
FILES_MATCHING PATTERN "*.h")
```
will extract and install header files from a source tree.
Some options may follow a `PATTERN` or `REGEX` expression and are applied only to files or directories matching them. The `EXCLUDE` option will skip the matched file or directory. The `PERMISSIONS` option overrides the permissions setting for the matched file or directory. For example the code
```
install(DIRECTORY icons scripts/ DESTINATION share/myproj
PATTERN "CVS" EXCLUDE
PATTERN "scripts/*"
PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ
GROUP_EXECUTE GROUP_READ)
```
will install the `icons` directory to `share/myproj/icons` and the `scripts` directory to `share/myproj`. The icons will get default file permissions, the scripts will be given specific permissions, and any `CVS` directories will be excluded.
The list of `dirs...` given to `DIRECTORY` and the install destination given to the directory install `DESTINATION` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions.
Custom Installation Logic
-------------------------
```
install([[SCRIPT <file>] [CODE <code>]]
[COMPONENT <component>] [EXCLUDE_FROM_ALL] [...])
```
The `SCRIPT` form will invoke the given CMake script files during installation. If the script file name is a relative path it will be interpreted with respect to the current source directory. The `CODE` form will invoke the given CMake code during installation. Code is specified as a single argument inside a double-quoted string. For example, the code
```
install(CODE "MESSAGE(\"Sample install message.\")")
```
will print a message during installation.
Installing Exports
------------------
```
install(EXPORT <export-name> DESTINATION <dir>
[NAMESPACE <namespace>] [[FILE <name>.cmake]|
[EXPORT_ANDROID_MK <name>.mk]]
[PERMISSIONS permissions...]
[CONFIGURATIONS [Debug|Release|...]]
[EXPORT_LINK_INTERFACE_LIBRARIES]
[COMPONENT <component>]
[EXCLUDE_FROM_ALL])
```
The `EXPORT` form generates and installs a CMake file containing code to import targets from the installation tree into another project. Target installations are associated with the export `<export-name>` using the `EXPORT` option of the `install(TARGETS)` signature documented above. The `NAMESPACE` option will prepend `<namespace>` to the target names as they are written to the import file. By default the generated file will be called `<export-name>.cmake` but the `FILE` option may be used to specify a different name. The value given to the `FILE` option must be a file name with the `.cmake` extension. If a `CONFIGURATIONS` option is given then the file will only be installed when one of the named configurations is installed. Additionally, the generated import file will reference only the matching target configurations. The `EXPORT_LINK_INTERFACE_LIBRARIES` keyword, if present, causes the contents of the properties matching `(IMPORTED_)?LINK_INTERFACE_LIBRARIES(_<CONFIG>)?` to be exported, when policy [`CMP0022`](../policy/cmp0022#policy:CMP0022 "CMP0022") is `NEW`. If a `COMPONENT` option is specified that does not match that given to the targets associated with `<export-name>` the behavior is undefined. If a library target is included in the export but a target to which it links is not included the behavior is unspecified.
In additon to cmake language files, the `EXPORT_ANDROID_MK` option maybe used to specifiy an export to the android ndk build system. The Android NDK supports the use of prebuilt libraries, both static and shared. This allows cmake to build the libraries of a project and make them available to an ndk build system complete with transitive dependencies, include flags and defines required to use the libraries.
The `EXPORT` form is useful to help outside projects use targets built and installed by the current project. For example, the code
```
install(TARGETS myexe EXPORT myproj DESTINATION bin)
install(EXPORT myproj NAMESPACE mp_ DESTINATION lib/myproj)
install(EXPORT_ANDROID_MK myexp DESTINATION share/ndk-modules)
```
will install the executable myexe to `<prefix>/bin` and code to import it in the file `<prefix>/lib/myproj/myproj.cmake` and `<prefix>/lib/share/ndk-modules/Android.mk`. An outside project may load this file with the include command and reference the `myexe` executable from the installation tree using the imported target name `mp_myexe` as if the target were built in its own tree.
Note
This command supercedes the [`install_targets()`](install_targets#command:install_targets "install_targets") command and the [`PRE_INSTALL_SCRIPT`](../prop_tgt/pre_install_script#prop_tgt:PRE_INSTALL_SCRIPT "PRE_INSTALL_SCRIPT") and [`POST_INSTALL_SCRIPT`](../prop_tgt/post_install_script#prop_tgt:POST_INSTALL_SCRIPT "POST_INSTALL_SCRIPT") target properties. It also replaces the `FILES` forms of the [`install_files()`](install_files#command:install_files "install_files") and [`install_programs()`](install_programs#command:install_programs "install_programs") commands. The processing order of these install rules relative to those generated by [`install_targets()`](install_targets#command:install_targets "install_targets"), [`install_files()`](install_files#command:install_files "install_files"), and [`install_programs()`](install_programs#command:install_programs "install_programs") commands is not defined.
cmake subdirs subdirs
=======
Deprecated. Use the [`add_subdirectory()`](add_subdirectory#command:add_subdirectory "add_subdirectory") command instead.
Add a list of subdirectories to the build.
```
subdirs(dir1 dir2 ...[EXCLUDE_FROM_ALL exclude_dir1 exclude_dir2 ...]
[PREORDER] )
```
Add a list of subdirectories to the build. The [`add_subdirectory()`](add_subdirectory#command:add_subdirectory "add_subdirectory") command should be used instead of `subdirs` although `subdirs` will still work. This will cause any CMakeLists.txt files in the sub directories to be processed by CMake. Any directories after the `PREORDER` flag are traversed first by makefile builds, the `PREORDER` flag has no effect on IDE projects. Any directories after the `EXCLUDE_FROM_ALL` marker will not be included in the top level makefile or project file. This is useful for having CMake create makefiles or projects for a set of examples in a project. You would want CMake to generate makefiles or project files for all the examples at the same time, but you would not want them to show up in the top level project or be built each time make is run from the top.
| programming_docs |
cmake continue continue
========
Continue to the top of enclosing foreach or while loop.
```
continue()
```
The `continue` command allows a cmake script to abort the rest of a block in a [`foreach()`](foreach#command:foreach "foreach") or [`while()`](while#command:while "while") loop, and start at the top of the next iteration. See also the [`break()`](break#command:break "break") command.
cmake cmake_minimum_required cmake\_minimum\_required
========================
Set the minimum required version of cmake for a project and update [Policy Settings](#policy-settings) to match the version given:
```
cmake_minimum_required(VERSION major.minor[.patch[.tweak]]
[FATAL_ERROR])
```
If the current version of CMake is lower than that required it will stop processing the project and report an error.
The `FATAL_ERROR` option is accepted but ignored by CMake 2.6 and higher. It should be specified so CMake versions 2.4 and lower fail with an error instead of just a warning.
Note
Call the `cmake_minimum_required()` command at the beginning of the top-level `CMakeLists.txt` file even before calling the [`project()`](project#command:project "project") command. It is important to establish version and policy settings before invoking other commands whose behavior they may affect. See also policy [`CMP0000`](../policy/cmp0000#policy:CMP0000 "CMP0000").
Calling `cmake_minimum_required()` inside a [`function()`](function#command:function "function") limits some effects to the function scope when invoked. Such calls should not be made with the intention of having global effects.
Policy Settings
---------------
The `cmake_minimum_required(VERSION)` command implicitly invokes the [`cmake_policy(VERSION)`](cmake_policy#command:cmake_policy "cmake_policy") command to specify that the current project code is written for the given version of CMake. All policies introduced in the specified version or earlier will be set to use NEW behavior. All policies introduced after the specified version will be unset. This effectively requests behavior preferred as of a given CMake version and tells newer CMake versions to warn about their new policies.
When a version higher than 2.4 is specified the command implicitly invokes:
```
cmake_policy(VERSION major[.minor[.patch[.tweak]]])
```
which sets the cmake policy version level to the version specified. When version 2.4 or lower is given the command implicitly invokes:
```
cmake_policy(VERSION 2.4)
```
which enables compatibility features for CMake 2.4 and lower.
cmake link_libraries link\_libraries
===============
Link libraries to all targets added later.
```
link_libraries([item1 [item2 [...]]]
[[debug|optimized|general] <item>] ...)
```
Specify libraries or flags to use when linking any targets created later in the current directory or below by commands such as [`add_executable()`](add_executable#command:add_executable "add_executable") or [`add_library()`](add_library#command:add_library "add_library"). See the [`target_link_libraries()`](target_link_libraries#command:target_link_libraries "target_link_libraries") command for meaning of arguments.
Note
The [`target_link_libraries()`](target_link_libraries#command:target_link_libraries "target_link_libraries") command should be preferred whenever possible. Library dependencies are chained automatically, so directory-wide specification of link libraries is rarely needed.
cmake variable_requires variable\_requires
==================
Disallowed. See CMake Policy [`CMP0035`](../policy/cmp0035#policy:CMP0035 "CMP0035").
Use the [`if()`](if#command:if "if") command instead.
Assert satisfaction of an option’s required variables.
```
variable_requires(TEST_VARIABLE RESULT_VARIABLE
REQUIRED_VARIABLE1
REQUIRED_VARIABLE2 ...)
```
The first argument (`TEST_VARIABLE`) is the name of the variable to be tested, if that variable is false nothing else is done. If `TEST_VARIABLE` is true, then the next argument (`RESULT_VARIABLE`) is a variable that is set to true if all the required variables are set. The rest of the arguments are variables that must be true or not set to NOTFOUND to avoid an error. If any are not true, an error is reported.
cmake unset unset
=====
Unset a variable, cache variable, or environment variable.
```
unset(<variable> [CACHE | PARENT_SCOPE])
```
Removes the specified variable causing it to become undefined. If `CACHE` is present then the variable is removed from the cache instead of the current scope.
If `PARENT_SCOPE` is present then the variable is removed from the scope above the current scope. See the same option in the [`set()`](set#command:set "set") command for further details.
`<variable>` can be an environment variable such as:
```
unset(ENV{LD_LIBRARY_PATH})
```
in which case the variable will be removed from the current environment.
cmake cmake_policy cmake\_policy
=============
Manage CMake Policy settings. See the [`cmake-policies(7)`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") manual for defined policies.
As CMake evolves it is sometimes necessary to change existing behavior in order to fix bugs or improve implementations of existing features. The CMake Policy mechanism is designed to help keep existing projects building as new versions of CMake introduce changes in behavior. Each new policy (behavioral change) is given an identifier of the form `CMP<NNNN>` where `<NNNN>` is an integer index. Documentation associated with each policy describes the `OLD` and `NEW` behavior and the reason the policy was introduced. Projects may set each policy to select the desired behavior. When CMake needs to know which behavior to use it checks for a setting specified by the project. If no setting is available the `OLD` behavior is assumed and a warning is produced requesting that the policy be set.
Setting Policies by CMake Version
---------------------------------
The `cmake_policy` command is used to set policies to `OLD` or `NEW` behavior. While setting policies individually is supported, we encourage projects to set policies based on CMake versions:
```
cmake_policy(VERSION major.minor[.patch[.tweak]])
```
Specify that the current CMake code is written for the given version of CMake. All policies introduced in the specified version or earlier will be set to use `NEW` behavior. All policies introduced after the specified version will be unset (unless the [`CMAKE_POLICY_DEFAULT_CMP<NNNN>`](# "CMAKE_POLICY_DEFAULT_CMP<NNNN>") variable sets a default). This effectively requests behavior preferred as of a given CMake version and tells newer CMake versions to warn about their new policies. The policy version specified must be at least 2.4 or the command will report an error.
Note that the [`cmake_minimum_required(VERSION)`](cmake_minimum_required#command:cmake_minimum_required "cmake_minimum_required") command implicitly calls `cmake_policy(VERSION)` too.
Setting Policies Explicitly
---------------------------
```
cmake_policy(SET CMP<NNNN> NEW)
cmake_policy(SET CMP<NNNN> OLD)
```
Tell CMake to use the `OLD` or `NEW` behavior for a given policy. Projects depending on the old behavior of a given policy may silence a policy warning by setting the policy state to `OLD`. Alternatively one may fix the project to work with the new behavior and set the policy state to `NEW`.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
Checking Policy Settings
------------------------
```
cmake_policy(GET CMP<NNNN> <variable>)
```
Check whether a given policy is set to `OLD` or `NEW` behavior. The output `<variable>` value will be `OLD` or `NEW` if the policy is set, and empty otherwise.
CMake Policy Stack
------------------
CMake keeps policy settings on a stack, so changes made by the cmake\_policy command affect only the top of the stack. A new entry on the policy stack is managed automatically for each subdirectory to protect its parents and siblings. CMake also manages a new entry for scripts loaded by [`include()`](include#command:include "include") and [`find_package()`](find_package#command:find_package "find_package") commands except when invoked with the `NO_POLICY_SCOPE` option (see also policy [`CMP0011`](../policy/cmp0011#policy:CMP0011 "CMP0011")). The `cmake_policy` command provides an interface to manage custom entries on the policy stack:
```
cmake_policy(PUSH)
cmake_policy(POP)
```
Each `PUSH` must have a matching `POP` to erase any changes. This is useful to make temporary changes to policy settings. Calls to the [`cmake_minimum_required(VERSION)`](cmake_minimum_required#command:cmake_minimum_required "cmake_minimum_required"), `cmake_policy(VERSION)`, or `cmake_policy(SET)` commands influence only the current top of the policy stack.
Commands created by the [`function()`](function#command:function "function") and [`macro()`](macro#command:macro "macro") commands record policy settings when they are created and use the pre-record policies when they are invoked. If the function or macro implementation sets policies, the changes automatically propagate up through callers until they reach the closest nested policy stack entry.
cmake build_name build\_name
===========
Disallowed. See CMake Policy [`CMP0036`](../policy/cmp0036#policy:CMP0036 "CMP0036").
Use `${CMAKE_SYSTEM}` and `${CMAKE_CXX_COMPILER}` instead.
```
build_name(variable)
```
Sets the specified variable to a string representing the platform and compiler settings. These values are now available through the [`CMAKE_SYSTEM`](../variable/cmake_system#variable:CMAKE_SYSTEM "CMAKE_SYSTEM") and [`CMAKE_CXX_COMPILER`](# "CMAKE_<LANG>_COMPILER") variables.
cmake add_compile_options add\_compile\_options
=====================
Adds options to the compilation of source files.
```
add_compile_options(<option> ...)
```
Adds options to the compiler command line for targets in the current directory and below that are added after this command is invoked. See documentation of the [`directory`](../prop_dir/compile_options#prop_dir:COMPILE_OPTIONS "COMPILE_OPTIONS") and [`target`](../prop_tgt/compile_options#prop_tgt:COMPILE_OPTIONS "COMPILE_OPTIONS") `COMPILE_OPTIONS` properties.
This command can be used to add any options, but alternative commands exist to add preprocessor definitions ([`target_compile_definitions()`](target_compile_definitions#command:target_compile_definitions "target_compile_definitions") and [`add_definitions()`](add_definitions#command:add_definitions "add_definitions")) or include directories ([`target_include_directories()`](target_include_directories#command:target_include_directories "target_include_directories") and [`include_directories()`](include_directories#command:include_directories "include_directories")).
Arguments to `add_compile_options` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake link_directories link\_directories
=================
Specify directories in which the linker will look for libraries.
```
link_directories(directory1 directory2 ...)
```
Specify the paths in which the linker should search for libraries. The command will apply only to targets created after it is called. Relative paths given to this command are interpreted as relative to the current source directory, see [`CMP0015`](../policy/cmp0015#policy:CMP0015 "CMP0015").
Note that this command is rarely necessary. Library locations returned by [`find_package()`](find_package#command:find_package "find_package") and [`find_library()`](find_library#command:find_library "find_library") are absolute paths. Pass these absolute library file paths directly to the [`target_link_libraries()`](target_link_libraries#command:target_link_libraries "target_link_libraries") command. CMake will ensure the linker finds them.
cmake mark_as_advanced mark\_as\_advanced
==================
Mark cmake cached variables as advanced.
```
mark_as_advanced([CLEAR|FORCE] VAR [VAR2 ...])
```
Mark the named cached variables as advanced. An advanced variable will not be displayed in any of the cmake GUIs unless the show advanced option is on. If `CLEAR` is the first argument advanced variables are changed back to unadvanced. If `FORCE` is the first argument, then the variable is made advanced. If neither `FORCE` nor `CLEAR` is specified, new values will be marked as advanced, but if the variable already has an advanced/non-advanced state, it will not be changed.
It does nothing in script mode.
cmake endfunction endfunction
===========
Ends a list of commands in a function block.
```
endfunction(expression)
```
See the [`function()`](function#command:function "function") command.
cmake ctest_coverage ctest\_coverage
===============
Perform the [CTest Coverage Step](../manual/ctest.1#ctest-coverage-step) as a [Dashboard Client](../manual/ctest.1#dashboard-client).
```
ctest_coverage([BUILD <build-dir>] [APPEND]
[LABELS <label>...]
[RETURN_VALUE <result-var>]
[CAPTURE_CMAKE_ERROR <result-var]
[QUIET]
)
```
Collect coverage tool results and stores them in `Coverage.xml` for submission with the [`ctest_submit()`](ctest_submit#command:ctest_submit "ctest_submit") command.
The options are:
`BUILD <build-dir>` Specify the top-level build directory. If not given, the [`CTEST_BINARY_DIRECTORY`](../variable/ctest_binary_directory#variable:CTEST_BINARY_DIRECTORY "CTEST_BINARY_DIRECTORY") variable is used.
`APPEND` Mark `Coverage.xml` for append to results previously submitted to a dashboard server since the last [`ctest_start()`](ctest_start#command:ctest_start "ctest_start") call. Append semantics are defined by the dashboard server in use. This does *not* cause results to be appended to a `.xml` file produced by a previous call to this command.
`LABELS` Filter the coverage report to include only source files labeled with at least one of the labels specified.
`RETURN_VALUE <result-var>` Store in the `<result-var>` variable `0` if coverage tools ran without error and non-zero otherwise.
`CAPTURE_CMAKE_ERROR <result-var>` Store in the `<result-var>` variable -1 if there are any errors running the command and prevent ctest from returning non-zero if an error occurs.
`QUIET` Suppress any CTest-specific non-error output that would have been printed to the console otherwise. The summary indicating how many lines of code were covered is unaffected by this option.
cmake fltk_wrap_ui fltk\_wrap\_ui
==============
Create FLTK user interfaces Wrappers.
```
fltk_wrap_ui(resultingLibraryName source1
source2 ... sourceN )
```
Produce .h and .cxx files for all the .fl and .fld files listed. The resulting .h and .cxx files will be added to a variable named `resultingLibraryName_FLTK_UI_SRCS` which should be added to your library.
cmake aux_source_directory aux\_source\_directory
======================
Find all source files in a directory.
```
aux_source_directory(<dir> <variable>)
```
Collects the names of all the source files in the specified directory and stores the list in the `<variable>` provided. This command is intended to be used by projects that use explicit template instantiation. Template instantiation files can be stored in a “Templates” subdirectory and collected automatically using this command to avoid manually listing all instantiations.
It is tempting to use this command to avoid writing the list of source files for a library or executable target. While this seems to work, there is no way for CMake to generate a build system that knows when a new source file has been added. Normally the generated build system knows when it needs to rerun CMake because the CMakeLists.txt file is modified to add a new source. When the source is just added to the directory without modifying this file, one would have to manually rerun CMake to generate a build system incorporating the new file.
cmake else else
====
Starts the else portion of an if block.
```
else(expression)
```
See the [`if()`](if#command:if "if") command.
cmake ctest_memcheck ctest\_memcheck
===============
Perform the [CTest MemCheck Step](../manual/ctest.1#ctest-memcheck-step) as a [Dashboard Client](../manual/ctest.1#dashboard-client).
```
ctest_memcheck([BUILD <build-dir>] [APPEND]
[START <start-number>]
[END <end-number>]
[STRIDE <stride-number>]
[EXCLUDE <exclude-regex>]
[INCLUDE <include-regex>]
[EXCLUDE_LABEL <label-exclude-regex>]
[INCLUDE_LABEL <label-include-regex>]
[EXCLUDE_FIXTURE <regex>]
[EXCLUDE_FIXTURE_SETUP <regex>]
[EXCLUDE_FIXTURE_CLEANUP <regex>]
[PARALLEL_LEVEL <level>]
[TEST_LOAD <threshold>]
[SCHEDULE_RANDOM <ON|OFF>]
[STOP_TIME <time-of-day>]
[RETURN_VALUE <result-var>]
[DEFECT_COUNT <defect-count-var>]
[QUIET]
)
```
Run tests with a dynamic analysis tool and store results in `MemCheck.xml` for submission with the [`ctest_submit()`](ctest_submit#command:ctest_submit "ctest_submit") command.
Most options are the same as those for the [`ctest_test()`](ctest_test#command:ctest_test "ctest_test") command.
The options unique to this command are:
`DEFECT_COUNT <defect-count-var>` Store in the `<defect-count-var>` the number of defects found.
cmake get_directory_property get\_directory\_property
========================
Get a property of `DIRECTORY` scope.
```
get_directory_property(<variable> [DIRECTORY <dir>] <prop-name>)
```
Store a property of directory scope in the named variable. If the property is not defined the empty-string is returned. The `DIRECTORY` argument specifies another directory from which to retrieve the property value. The specified directory must have already been traversed by CMake.
```
get_directory_property(<variable> [DIRECTORY <dir>]
DEFINITION <var-name>)
```
Get a variable definition from a directory. This form is useful to get a variable definition from another directory.
See also the more general [`get_property()`](get_property#command:get_property "get_property") command.
cmake while while
=====
Evaluate a group of commands while a condition is true
```
while(condition)
COMMAND1(ARGS ...)
COMMAND2(ARGS ...)
...
endwhile(condition)
```
All commands between while and the matching [`endwhile()`](endwhile#command:endwhile "endwhile") are recorded without being invoked. Once the [`endwhile()`](endwhile#command:endwhile "endwhile") is evaluated, the recorded list of commands is invoked as long as the condition is true. The condition is evaluated using the same logic as the [`if()`](if#command:if "if") command.
cmake make_directory make\_directory
===============
Deprecated. Use the [`file(MAKE_DIRECTORY)`](file#command:file "file") command instead.
```
make_directory(directory)
```
Creates the specified directory. Full paths should be given. Any parent directories that do not exist will also be created. Use with care.
cmake ctest_build ctest\_build
============
Perform the [CTest Build Step](../manual/ctest.1#ctest-build-step) as a [Dashboard Client](../manual/ctest.1#dashboard-client).
```
ctest_build([BUILD <build-dir>] [APPEND]
[CONFIGURATION <config>]
[FLAGS <flags>]
[PROJECT_NAME <project-name>]
[TARGET <target-name>]
[NUMBER_ERRORS <num-err-var>]
[NUMBER_WARNINGS <num-warn-var>]
[RETURN_VALUE <result-var>]
[CAPTURE_CMAKE_ERROR <result-var>]
)
```
Build the project and store results in `Build.xml` for submission with the [`ctest_submit()`](ctest_submit#command:ctest_submit "ctest_submit") command.
The [`CTEST_BUILD_COMMAND`](../variable/ctest_build_command#variable:CTEST_BUILD_COMMAND "CTEST_BUILD_COMMAND") variable may be set to explicitly specify the build command line. Otherwise the build command line is computed automatically based on the options given.
The options are:
`BUILD <build-dir>` Specify the top-level build directory. If not given, the [`CTEST_BINARY_DIRECTORY`](../variable/ctest_binary_directory#variable:CTEST_BINARY_DIRECTORY "CTEST_BINARY_DIRECTORY") variable is used.
`APPEND` Mark `Build.xml` for append to results previously submitted to a dashboard server since the last [`ctest_start()`](ctest_start#command:ctest_start "ctest_start") call. Append semantics are defined by the dashboard server in use. This does *not* cause results to be appended to a `.xml` file produced by a previous call to this command.
`CONFIGURATION <config>` Specify the build configuration (e.g. `Debug`). If not specified the `CTEST_BUILD_CONFIGURATION` variable will be checked. Otherwise the `-C <cfg>` option given to the [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") command will be used, if any.
`FLAGS <flags>` Pass additional arguments to the underlying build command. If not specified the `CTEST_BUILD_FLAGS` variable will be checked. This can, e.g., be used to trigger a parallel build using the `-j` option of make. See the [`ProcessorCount`](../module/processorcount#module:ProcessorCount "ProcessorCount") module for an example.
`PROJECT_NAME <project-name>` Set the name of the project to build. This should correspond to the top-level call to the [`project()`](project#command:project "project") command. If not specified the `CTEST_PROJECT_NAME` variable will be checked.
`TARGET <target-name>` Specify the name of a target to build. If not specified the `CTEST_BUILD_TARGET` variable will be checked. Otherwise the default target will be built. This is the “all” target (called `ALL_BUILD` in [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators)).
`NUMBER_ERRORS <num-err-var>` Store the number of build errors detected in the given variable.
`NUMBER_WARNINGS <num-warn-var>` Store the number of build warnings detected in the given variable.
`RETURN_VALUE <result-var>` Store the return value of the native build tool in the given variable.
`CAPTURE_CMAKE_ERROR <result-var>` Store in the `<result-var>` variable -1 if there are any errors running the command and prevent ctest from returning non-zero if an error occurs.
`QUIET` Suppress any CTest-specific non-error output that would have been printed to the console otherwise. The summary of warnings / errors, as well as the output from the native build tool is unaffected by this option.
| programming_docs |
cmake set_property set\_property
=============
Set a named property in a given scope.
```
set_property(<GLOBAL |
DIRECTORY [dir] |
TARGET [target1 [target2 ...]] |
SOURCE [src1 [src2 ...]] |
INSTALL [file1 [file2 ...]] |
TEST [test1 [test2 ...]] |
CACHE [entry1 [entry2 ...]]>
[APPEND] [APPEND_STRING]
PROPERTY <name> [value1 [value2 ...]])
```
Set one property on zero or more objects of a scope. The first argument determines the scope in which the property is set. It must be one of the following:
`GLOBAL` Scope is unique and does not accept a name.
`DIRECTORY` Scope defaults to the current directory but another directory (already processed by CMake) may be named by full or relative path.
`TARGET` Scope may name zero or more existing targets.
`SOURCE` Scope may name zero or more source files. Note that source file properties are visible only to targets added in the same directory (CMakeLists.txt).
`INSTALL`
Scope may name zero or more installed file paths. These are made available to CPack to influence deployment.
Both the property key and value may use generator expressions. Specific properties may apply to installed files and/or directories.
Path components have to be separated by forward slashes, must be normalized and are case sensitive.
To reference the installation prefix itself with a relative path use “.”.
Currently installed file properties are only defined for the WIX generator where the given paths are relative to the installation prefix.
`TEST` Scope may name zero or more existing tests.
`CACHE` Scope must name zero or more cache existing entries. The required `PROPERTY` option is immediately followed by the name of the property to set. Remaining arguments are used to compose the property value in the form of a semicolon-separated list. If the `APPEND` option is given the list is appended to any existing property value. If the `APPEND_STRING` option is given the string is append to any existing property value as string, i.e. it results in a longer string and not a list of strings.
See the [`cmake-properties(7)`](../manual/cmake-properties.7#manual:cmake-properties(7) "cmake-properties(7)") manual for a list of properties in each scope.
cmake find_path find\_path
==========
A short-hand signature is:
```
find_path (<VAR> name1 [path1 path2 ...])
```
The general signature is:
```
find_path (
<VAR>
name | NAMES name1 [name2 ...]
[HINTS path1 [path2 ... ENV var]]
[PATHS path1 [path2 ... ENV var]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[DOC "cache documentation string"]
[NO_DEFAULT_PATH]
[NO_CMAKE_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[NO_SYSTEM_ENVIRONMENT_PATH]
[NO_CMAKE_SYSTEM_PATH]
[CMAKE_FIND_ROOT_PATH_BOTH |
ONLY_CMAKE_FIND_ROOT_PATH |
NO_CMAKE_FIND_ROOT_PATH]
)
```
This command is used to find a directory containing the named file. A cache entry named by `<VAR>` is created to store the result of this command. If the file in a directory is found the result is stored in the variable and the search will not be repeated unless the variable is cleared. If nothing is found, the result will be `<VAR>-NOTFOUND`, and the search will be attempted again the next time find\_path is invoked with the same variable.
Options include:
`NAMES`
Specify one or more possible names for the file in a directory.
When using this to specify names with and without a version suffix, we recommend specifying the unversioned name first so that locally-built packages can be found before those provided by distributions.
`HINTS, PATHS` Specify directories to search in addition to the default locations. The `ENV var` sub-option reads paths from a system environment variable.
`PATH_SUFFIXES` Specify additional subdirectories to check below each directory location otherwise considered.
`DOC` Specify the documentation string for the `<VAR>` cache entry. If `NO_DEFAULT_PATH` is specified, then no additional paths are added to the search. If `NO_DEFAULT_PATH` is not specified, the search process is as follows:
1. Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a `-DVAR=value`. The values are interpreted as [;-lists](../manual/cmake-language.7#cmake-language-lists). This can be skipped if `NO_CMAKE_PATH` is passed.
* `<prefix>/include/<arch>` if [`CMAKE_LIBRARY_ARCHITECTURE`](../variable/cmake_library_architecture#variable:CMAKE_LIBRARY_ARCHITECTURE "CMAKE_LIBRARY_ARCHITECTURE") is set, and `<prefix>/include` for each `<prefix>` in [`CMAKE_PREFIX_PATH`](../variable/cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH")
* [`CMAKE_INCLUDE_PATH`](../variable/cmake_include_path#variable:CMAKE_INCLUDE_PATH "CMAKE_INCLUDE_PATH")
* [`CMAKE_FRAMEWORK_PATH`](../variable/cmake_framework_path#variable:CMAKE_FRAMEWORK_PATH "CMAKE_FRAMEWORK_PATH")
2. Search paths specified in cmake-specific environment variables. These are intended to be set in the user’s shell configuration, and therefore use the host’s native path separator (`;` on Windows and `:` on UNIX). This can be skipped if `NO_CMAKE_ENVIRONMENT_PATH` is passed.
* `<prefix>/include/<arch>` if [`CMAKE_LIBRARY_ARCHITECTURE`](../variable/cmake_library_architecture#variable:CMAKE_LIBRARY_ARCHITECTURE "CMAKE_LIBRARY_ARCHITECTURE") is set, and `<prefix>/include` for each `<prefix>` in [`CMAKE_PREFIX_PATH`](../variable/cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH")
* [`CMAKE_INCLUDE_PATH`](../variable/cmake_include_path#variable:CMAKE_INCLUDE_PATH "CMAKE_INCLUDE_PATH")
* [`CMAKE_FRAMEWORK_PATH`](../variable/cmake_framework_path#variable:CMAKE_FRAMEWORK_PATH "CMAKE_FRAMEWORK_PATH")
3. Search the paths specified by the `HINTS` option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the `PATHS` option.
4. Search the standard system environment variables. This can be skipped if `NO_SYSTEM_ENVIRONMENT_PATH` is an argument.
* Directories in `INCLUDE`. On Windows hosts: `<prefix>/include/<arch>` if [`CMAKE_LIBRARY_ARCHITECTURE`](../variable/cmake_library_architecture#variable:CMAKE_LIBRARY_ARCHITECTURE "CMAKE_LIBRARY_ARCHITECTURE") is set, and `<prefix>/include` for each `<prefix>/[s]bin` in `PATH`, and `<entry>/include` for other entries in `PATH`, and the directories in `PATH` itself.
5. Search cmake variables defined in the Platform files for the current system. This can be skipped if `NO_CMAKE_SYSTEM_PATH` is passed.
* `<prefix>/include/<arch>` if [`CMAKE_LIBRARY_ARCHITECTURE`](../variable/cmake_library_architecture#variable:CMAKE_LIBRARY_ARCHITECTURE "CMAKE_LIBRARY_ARCHITECTURE") is set, and `<prefix>/include` for each `<prefix>` in [`CMAKE_SYSTEM_PREFIX_PATH`](../variable/cmake_system_prefix_path#variable:CMAKE_SYSTEM_PREFIX_PATH "CMAKE_SYSTEM_PREFIX_PATH")
* [`CMAKE_SYSTEM_INCLUDE_PATH`](../variable/cmake_system_include_path#variable:CMAKE_SYSTEM_INCLUDE_PATH "CMAKE_SYSTEM_INCLUDE_PATH")
* [`CMAKE_SYSTEM_FRAMEWORK_PATH`](../variable/cmake_system_framework_path#variable:CMAKE_SYSTEM_FRAMEWORK_PATH "CMAKE_SYSTEM_FRAMEWORK_PATH")
6. Search the paths specified by the PATHS option or in the short-hand version of the command. These are typically hard-coded guesses.
On OS X the [`CMAKE_FIND_FRAMEWORK`](../variable/cmake_find_framework#variable:CMAKE_FIND_FRAMEWORK "CMAKE_FIND_FRAMEWORK") and [`CMAKE_FIND_APPBUNDLE`](../variable/cmake_find_appbundle#variable:CMAKE_FIND_APPBUNDLE "CMAKE_FIND_APPBUNDLE") variables determine the order of preference between Apple-style and unix-style package components.
The CMake variable [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") specifies one or more directories to be prepended to all other search directories. This effectively “re-roots” the entire search under given locations. Paths which are descendants of the [`CMAKE_STAGING_PREFIX`](../variable/cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX") are excluded from this re-rooting, because that variable is always a path on the host system. By default the [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") is empty.
The [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") variable can also be used to specify exactly one directory to use as a prefix. Setting [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") also has other effects. See the documentation for that variable for more.
These variables are especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") are searched, then the [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") directory is searched, and then the non-rooted directories will be searched. The default behavior can be adjusted by setting [`CMAKE_FIND_ROOT_PATH_MODE_INCLUDE`](../variable/cmake_find_root_path_mode_include#variable:CMAKE_FIND_ROOT_PATH_MODE_INCLUDE "CMAKE_FIND_ROOT_PATH_MODE_INCLUDE"). This behavior can be manually overridden on a per-call basis using options:
`CMAKE_FIND_ROOT_PATH_BOTH` Search in the order described above.
`NO_CMAKE_FIND_ROOT_PATH` Do not use the [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") variable.
`ONLY_CMAKE_FIND_ROOT_PATH` Search only the re-rooted directories and directories below [`CMAKE_STAGING_PREFIX`](../variable/cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX"). The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the `NO_*` options:
```
find_path (<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH)
find_path (<VAR> NAMES name)
```
Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.
When searching for frameworks, if the file is specified as `A/b.h`, then the framework search will look for `A.framework/Headers/b.h`. If that is found the path will be set to the path to the framework. CMake will convert this to the correct `-F` option to include the file.
cmake get_target_property get\_target\_property
=====================
Get a property from a target.
```
get_target_property(VAR target property)
```
Get a property from a target. The value of the property is stored in the variable `VAR`. If the property is not found, `VAR` will be set to “NOTFOUND”. Use [`set_target_properties()`](set_target_properties#command:set_target_properties "set_target_properties") to set property values. Properties are usually used to control how a target is built, but some query the target instead. This command can get properties for any target so far created. The targets do not need to be in the current `CMakeLists.txt` file.
See also the more general [`get_property()`](get_property#command:get_property "get_property") command.
cmake cmake_parse_arguments cmake\_parse\_arguments
=======================
`cmake_parse_arguments` is intended to be used in macros or functions for parsing the arguments given to that macro or function. It processes the arguments and defines a set of variables which hold the values of the respective options.
```
cmake_parse_arguments(<prefix> <options> <one_value_keywords>
<multi_value_keywords> args...)
cmake_parse_arguments(PARSE_ARGV N <prefix> <options> <one_value_keywords>
<multi_value_keywords>)
```
The first signature reads processes arguments passed in the `args...`. This may be used in either a [`macro()`](macro#command:macro "macro") or a [`function()`](function#command:function "function").
The `PARSE_ARGV` signature is only for use in a [`function()`](function#command:function "function") body. In this case the arguments that are parsed come from the `ARGV#` variables of the calling function. The parsing starts with the Nth argument, where `N` is an unsigned integer. This allows for the values to have special characters like `;` in them.
The `<options>` argument contains all options for the respective macro, i.e. keywords which can be used when calling the macro without any value following, like e.g. the `OPTIONAL` keyword of the [`install()`](install#command:install "install") command.
The `<one_value_keywords>` argument contains all keywords for this macro which are followed by one value, like e.g. `DESTINATION` keyword of the [`install()`](install#command:install "install") command.
The `<multi_value_keywords>` argument contains all keywords for this macro which can be followed by more than one value, like e.g. the `TARGETS` or `FILES` keywords of the [`install()`](install#command:install "install") command.
Note
All keywords shall be unique. I.e. every keyword shall only be specified once in either `<options>`, `<one_value_keywords>` or `<multi_value_keywords>`. A warning will be emitted if uniqueness is violated.
When done, `cmake_parse_arguments` will have defined for each of the keywords listed in `<options>`, `<one_value_keywords>` and `<multi_value_keywords>` a variable composed of the given `<prefix>` followed by `"_"` and the name of the respective keyword. These variables will then hold the respective value from the argument list. For the `<options>` keywords this will be `TRUE` or `FALSE`.
All remaining arguments are collected in a variable `<prefix>_UNPARSED_ARGUMENTS`, this can be checked afterwards to see whether your macro was called with unrecognized parameters.
As an example here a `my_install()` macro, which takes similar arguments as the real [`install()`](install#command:install "install") command:
```
function(MY_INSTALL)
set(options OPTIONAL FAST)
set(oneValueArgs DESTINATION RENAME)
set(multiValueArgs TARGETS CONFIGURATIONS)
cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}"
"${multiValueArgs}" ${ARGN} )
# ...
```
Assume `my_install()` has been called like this:
```
my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub)
```
After the `cmake_parse_arguments` call the macro will have set the following variables:
```
MY_INSTALL_OPTIONAL = TRUE
MY_INSTALL_FAST = FALSE (was not used in call to my_install)
MY_INSTALL_DESTINATION = "bin"
MY_INSTALL_RENAME = "" (was not used)
MY_INSTALL_TARGETS = "foo;bar"
MY_INSTALL_CONFIGURATIONS = "" (was not used)
MY_INSTALL_UNPARSED_ARGUMENTS = "blub" (nothing expected after "OPTIONAL")
```
You can then continue and process these variables.
Keywords terminate lists of values, e.g. if directly after a one\_value\_keyword another recognized keyword follows, this is interpreted as the beginning of the new option. E.g. `my_install(TARGETS foo DESTINATION OPTIONAL)` would result in `MY_INSTALL_DESTINATION` set to `"OPTIONAL"`, but as `OPTIONAL` is a keyword itself `MY_INSTALL_DESTINATION` will be empty and `MY_INSTALL_OPTIONAL` will therefore be set to `TRUE`.
cmake ctest_submit ctest\_submit
=============
Perform the [CTest Submit Step](../manual/ctest.1#ctest-submit-step) as a [Dashboard Client](../manual/ctest.1#dashboard-client).
```
ctest_submit([PARTS <part>...] [FILES <file>...]
[HTTPHEADER <header>]
[RETRY_COUNT <count>]
[RETRY_DELAY <delay>]
[RETURN_VALUE <result-var>]
[QUIET]
)
```
Submit results to a dashboard server. By default all available parts are submitted.
The options are:
`PARTS <part>...`
Specify a subset of parts to submit. Valid part names are:
```
Start = nothing
Update = ctest_update results, in Update.xml
Configure = ctest_configure results, in Configure.xml
Build = ctest_build results, in Build.xml
Test = ctest_test results, in Test.xml
Coverage = ctest_coverage results, in Coverage.xml
MemCheck = ctest_memcheck results, in DynamicAnalysis.xml
Notes = Files listed by CTEST_NOTES_FILES, in Notes.xml
ExtraFiles = Files listed by CTEST_EXTRA_SUBMIT_FILES
Upload = Files prepared for upload by ctest_upload(), in Upload.xml
Submit = nothing
```
`FILES <file>...` Specify an explicit list of specific files to be submitted. Each individual file must exist at the time of the call.
`HTTPHEADER <HTTP-header>` Specify HTTP header to be included in the request to CDash during submission. This suboption can be repeated several times.
`RETRY_COUNT <count>` Specify how many times to retry a timed-out submission.
`RETRY_DELAY <delay>` Specify how long (in seconds) to wait after a timed-out submission before attempting to re-submit.
`RETURN_VALUE <result-var>` Store in the `<result-var>` variable `0` for success and non-zero on failure.
`QUIET` Suppress all non-error messages that would have otherwise been printed to the console. Submit to CDash Upload API
--------------------------
```
ctest_submit(CDASH_UPLOAD <file> [CDASH_UPLOAD_TYPE <type>]
[HTTPHEADER <header>]
[RETRY_COUNT <count>]
[RETRY_DELAY <delay>]
[QUIET])
```
This second signature is used to upload files to CDash via the CDash file upload API. The api first sends a request to upload to CDash along with a content hash of the file. If CDash does not already have the file, then it is uploaded. Along with the file, a CDash type string is specified to tell CDash which handler to use to process the data.
This signature accepts the `HTTPHEADER`, `RETRY_COUNT`, `RETRY_DELAY`, and `QUIET` options as described above.
cmake list list
====
List operations.
```
list(LENGTH <list> <output variable>)
list(GET <list> <element index> [<element index> ...]
<output variable>)
list(APPEND <list> [<element> ...])
list(FILTER <list> <INCLUDE|EXCLUDE> REGEX <regular_expression>)
list(FIND <list> <value> <output variable>)
list(INSERT <list> <element_index> <element> [<element> ...])
list(REMOVE_ITEM <list> <value> [<value> ...])
list(REMOVE_AT <list> <index> [<index> ...])
list(REMOVE_DUPLICATES <list>)
list(REVERSE <list>)
list(SORT <list>)
```
`LENGTH` will return a given list’s length.
`GET` will return list of elements specified by indices from the list.
`APPEND` will append elements to the list.
`FILTER` will include or remove items from the list that match the mode’s pattern. In `REGEX` mode, items will be matched against the given regular expression. For more information on regular expressions see also the [`string()`](string#command:string "string") command.
`FIND` will return the index of the element specified in the list or -1 if it wasn’t found.
`INSERT` will insert elements to the list to the specified location.
`REMOVE_AT` and `REMOVE_ITEM` will remove items from the list. The difference is that `REMOVE_ITEM` will remove the given items, while `REMOVE_AT` will remove the items at the given indices.
`REMOVE_DUPLICATES` will remove duplicated items in the list.
`REVERSE` reverses the contents of the list in-place.
`SORT` sorts the list in-place alphabetically.
The list subcommands `APPEND`, `INSERT`, `FILTER`, `REMOVE_AT`, `REMOVE_ITEM`, `REMOVE_DUPLICATES`, `REVERSE` and `SORT` may create new values for the list within the current CMake variable scope. Similar to the [`set()`](set#command:set "set") command, the LIST command creates new variable values in the current scope, even if the list itself is actually defined in a parent scope. To propagate the results of these operations upwards, use [`set()`](set#command:set "set") with `PARENT_SCOPE`, [`set()`](set#command:set "set") with `CACHE INTERNAL`, or some other means of value propagation.
NOTES: A list in cmake is a `;` separated group of strings. To create a list the set command can be used. For example, `set(var a b c d e)` creates a list with `a;b;c;d;e`, and `set(var "a b c d e")` creates a string or a list with one item in it. (Note macro arguments are not variables, and therefore cannot be used in LIST commands.)
When specifying index values, if `<element index>` is 0 or greater, it is indexed from the beginning of the list, with 0 representing the first list element. If `<element index>` is -1 or lesser, it is indexed from the end of the list, with -1 representing the last list element. Be careful when counting with negative indices: they do not start from 0. -0 is equivalent to 0, the first list element.
| programming_docs |
cmake ctest_read_custom_files ctest\_read\_custom\_files
==========================
read CTestCustom files.
```
ctest_read_custom_files( directory ... )
```
Read all the CTestCustom.ctest or CTestCustom.cmake files from the given directory.
By default, invoking [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") without a script will read custom files from the binary directory.
cmake endmacro endmacro
========
Ends a list of commands in a macro block.
```
endmacro(expression)
```
See the [`macro()`](macro#command:macro "macro") command.
cmake include include
=======
Load and run CMake code from a file or module.
```
include(<file|module> [OPTIONAL] [RESULT_VARIABLE <VAR>]
[NO_POLICY_SCOPE])
```
Load and run CMake code from the file given. Variable reads and writes access the scope of the caller (dynamic scoping). If `OPTIONAL` is present, then no error is raised if the file does not exist. If `RESULT_VARIABLE` is given the variable will be set to the full filename which has been included or NOTFOUND if it failed.
If a module is specified instead of a file, the file with name `<modulename>.cmake` is searched first in [`CMAKE_MODULE_PATH`](../variable/cmake_module_path#variable:CMAKE_MODULE_PATH "CMAKE_MODULE_PATH"), then in the CMake module directory. There is one exception to this: if the file which calls `include()` is located itself in the CMake builtin module directory, then first the CMake builtin module directory is searched and [`CMAKE_MODULE_PATH`](../variable/cmake_module_path#variable:CMAKE_MODULE_PATH "CMAKE_MODULE_PATH") afterwards. See also policy [`CMP0017`](../policy/cmp0017#policy:CMP0017 "CMP0017").
See the [`cmake_policy()`](cmake_policy#command:cmake_policy "cmake_policy") command documentation for discussion of the `NO_POLICY_SCOPE` option.
cmake get_test_property get\_test\_property
===================
Get a property of the test.
```
get_test_property(test property VAR)
```
Get a property from the test. The value of the property is stored in the variable `VAR`. If the test or property is not found, `VAR` will be set to “NOTFOUND”. For a list of standard properties you can type `cmake --help-property-list`.
See also the more general [`get_property()`](get_property#command:get_property "get_property") command.
cmake ctest_configure ctest\_configure
================
Perform the [CTest Configure Step](../manual/ctest.1#ctest-configure-step) as a [Dashboard Client](../manual/ctest.1#dashboard-client).
```
ctest_configure([BUILD <build-dir>] [SOURCE <source-dir>] [APPEND]
[OPTIONS <options>] [RETURN_VALUE <result-var>] [QUIET]
[CAPTURE_CMAKE_ERROR <result-var>])
```
Configure the project build tree and record results in `Configure.xml` for submission with the [`ctest_submit()`](ctest_submit#command:ctest_submit "ctest_submit") command.
The options are:
`BUILD <build-dir>` Specify the top-level build directory. If not given, the [`CTEST_BINARY_DIRECTORY`](../variable/ctest_binary_directory#variable:CTEST_BINARY_DIRECTORY "CTEST_BINARY_DIRECTORY") variable is used.
`SOURCE <source-dir>` Specify the source directory. If not given, the [`CTEST_SOURCE_DIRECTORY`](../variable/ctest_source_directory#variable:CTEST_SOURCE_DIRECTORY "CTEST_SOURCE_DIRECTORY") variable is used.
`APPEND` Mark `Configure.xml` for append to results previously submitted to a dashboard server since the last [`ctest_start()`](ctest_start#command:ctest_start "ctest_start") call. Append semantics are defined by the dashboard server in use. This does *not* cause results to be appended to a `.xml` file produced by a previous call to this command.
`OPTIONS <options>` Specify command-line arguments to pass to the configuration tool.
`RETURN_VALUE <result-var>` Store in the `<result-var>` variable the return value of the native configuration tool.
`CAPTURE_CMAKE_ERROR <result-var>` Store in the `<result-var>` variable -1 if there are any errors running the command and prevent ctest from returning non-zero if an error occurs.
`QUIET` Suppress any CTest-specific non-error messages that would have otherwise been printed to the console. Output from the underlying configure command is not affected.
cmake get_property get\_property
=============
Get a property.
```
get_property(<variable>
<GLOBAL |
DIRECTORY [dir] |
TARGET <target> |
SOURCE <source> |
INSTALL <file> |
TEST <test> |
CACHE <entry> |
VARIABLE>
PROPERTY <name>
[SET | DEFINED | BRIEF_DOCS | FULL_DOCS])
```
Get one property from one object in a scope. The first argument specifies the variable in which to store the result. The second argument determines the scope from which to get the property. It must be one of the following:
`GLOBAL` Scope is unique and does not accept a name.
`DIRECTORY` Scope defaults to the current directory but another directory (already processed by CMake) may be named by full or relative path.
`TARGET` Scope must name one existing target.
`SOURCE` Scope must name one source file.
`INSTALL` Scope must name one installed file path.
`TEST` Scope must name one existing test.
`CACHE` Scope must name one cache entry.
`VARIABLE` Scope is unique and does not accept a name. The required `PROPERTY` option is immediately followed by the name of the property to get. If the property is not set an empty value is returned. If the `SET` option is given the variable is set to a boolean value indicating whether the property has been set. If the `DEFINED` option is given the variable is set to a boolean value indicating whether the property has been defined such as with the [`define_property()`](define_property#command:define_property "define_property") command. If `BRIEF_DOCS` or `FULL_DOCS` is given then the variable is set to a string containing documentation for the requested property. If documentation is requested for a property that has not been defined `NOTFOUND` is returned.
cmake create_test_sourcelist create\_test\_sourcelist
========================
Create a test driver and source list for building test programs.
```
create_test_sourcelist(sourceListName driverName
test1 test2 test3
EXTRA_INCLUDE include.h
FUNCTION function)
```
A test driver is a program that links together many small tests into a single executable. This is useful when building static executables with large libraries to shrink the total required size. The list of source files needed to build the test driver will be in `sourceListName`. `driverName` is the name of the test driver program. The rest of the arguments consist of a list of test source files, can be semicolon separated. Each test source file should have a function in it that is the same name as the file with no extension (foo.cxx should have int foo(int, char\*[]);) `driverName` will be able to call each of the tests by name on the command line. If `EXTRA_INCLUDE` is specified, then the next argument is included into the generated file. If `FUNCTION` is specified, then the next argument is taken as a function name that is passed a pointer to ac and av. This can be used to add extra command line processing to each test. The `CMAKE_TESTDRIVER_BEFORE_TESTMAIN` cmake variable can be set to have code that will be placed directly before calling the test main function. `CMAKE_TESTDRIVER_AFTER_TESTMAIN` can be set to have code that will be placed directly after the call to the test main function.
cmake target_include_directories target\_include\_directories
============================
Add include directories to a target.
```
target_include_directories(<target> [SYSTEM] [BEFORE]
<INTERFACE|PUBLIC|PRIVATE> [items1...]
[<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
```
Specify include directories to use when compiling a given target. The named `<target>` must have been created by a command such as [`add_executable()`](add_executable#command:add_executable "add_executable") or [`add_library()`](add_library#command:add_library "add_library") and must not be an [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target.
If `BEFORE` is specified, the content will be prepended to the property instead of being appended.
The `INTERFACE`, `PUBLIC` and `PRIVATE` keywords are required to specify the scope of the following arguments. `PRIVATE` and `PUBLIC` items will populate the [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES") property of `<target>`. `PUBLIC` and `INTERFACE` items will populate the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") property of `<target>`. The following arguments specify include directories.
Specified include directories may be absolute paths or relative paths. Repeated calls for the same <target> append items in the order called. If `SYSTEM` is specified, the compiler will be told the directories are meant as system include directories on some platforms (signalling this setting might achieve effects such as the compiler skipping warnings, or these fixed-install system files not being considered in dependency calculations - see compiler docs). If `SYSTEM` is used together with `PUBLIC` or `INTERFACE`, the [`INTERFACE_SYSTEM_INCLUDE_DIRECTORIES`](../prop_tgt/interface_system_include_directories#prop_tgt:INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "INTERFACE_SYSTEM_INCLUDE_DIRECTORIES") target property will be populated with the specified directories.
Arguments to `target_include_directories` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
Include directories usage requirements commonly differ between the build-tree and the install-tree. The `BUILD_INTERFACE` and `INSTALL_INTERFACE` generator expressions can be used to describe separate usage requirements based on the usage location. Relative paths are allowed within the `INSTALL_INTERFACE` expression and are interpreted relative to the installation prefix. For example:
```
target_include_directories(mylib PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/mylib>
$<INSTALL_INTERFACE:include/mylib> # <prefix>/include/mylib
)
```
Creating Relocatable Packages
-----------------------------
Note that it is not advisable to populate the `INSTALL_INTERFACE` of the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") of a target with absolute paths to the include directories of dependencies. That would hard-code into installed packages the include directory paths for dependencies **as found on the machine the package was made on**.
The `INSTALL_INTERFACE` of the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") is only suitable for specifying the required include directories for headers provided with the target itself, not those provided by the transitive dependencies listed in its [`INTERFACE_LINK_LIBRARIES`](../prop_tgt/interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES") target property. Those dependencies should themselves be targets that specify their own header locations in [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES").
See the [Creating Relocatable Packages](../manual/cmake-packages.7#creating-relocatable-packages) section of the [`cmake-packages(7)`](../manual/cmake-packages.7#manual:cmake-packages(7) "cmake-packages(7)") manual for discussion of additional care that must be taken when specifying usage requirements while creating packages for redistribution.
cmake subdir_depends subdir\_depends
===============
Disallowed. See CMake Policy [`CMP0029`](../policy/cmp0029#policy:CMP0029 "CMP0029").
Does nothing.
```
subdir_depends(subdir dep1 dep2 ...)
```
Does not do anything. This command used to help projects order parallel builds correctly. This functionality is now automatic.
cmake set_target_properties set\_target\_properties
=======================
Targets can have properties that affect how they are built.
```
set_target_properties(target1 target2 ...
PROPERTIES prop1 value1
prop2 value2 ...)
```
Set properties on a target. The syntax for the command is to list all the files you want to change, and then provide the values you want to set next. You can use any prop value pair you want and extract it later with the [`get_property()`](get_property#command:get_property "get_property") or [`get_target_property()`](get_target_property#command:get_target_property "get_target_property") command.
See [Properties on Targets](../manual/cmake-properties.7#target-properties) for the list of properties known to CMake.
cmake remove_definitions remove\_definitions
===================
Removes -D define flags added by [`add_definitions()`](add_definitions#command:add_definitions "add_definitions").
```
remove_definitions(-DFOO -DBAR ...)
```
Removes flags (added by [`add_definitions()`](add_definitions#command:add_definitions "add_definitions")) from the compiler command line for sources in the current directory and below.
cmake ctest_start ctest\_start
============
Starts the testing for a given model
```
ctest_start(Model [TRACK <track>] [APPEND] [source [binary]] [QUIET])
```
Starts the testing for a given model. The command should be called after the binary directory is initialized. If the ‘source’ and ‘binary’ directory are not specified, it reads the [`CTEST_SOURCE_DIRECTORY`](../variable/ctest_source_directory#variable:CTEST_SOURCE_DIRECTORY "CTEST_SOURCE_DIRECTORY") and [`CTEST_BINARY_DIRECTORY`](../variable/ctest_binary_directory#variable:CTEST_BINARY_DIRECTORY "CTEST_BINARY_DIRECTORY"). If the track is specified, the submissions will go to the specified track. If APPEND is used, the existing TAG is used rather than creating a new one based on the current time stamp. If `QUIET` is used, CTest will suppress any non-error messages that it otherwise would have printed to the console.
If the [`CTEST_CHECKOUT_COMMAND`](../variable/ctest_checkout_command#variable:CTEST_CHECKOUT_COMMAND "CTEST_CHECKOUT_COMMAND") variable (or the [`CTEST_CVS_CHECKOUT`](../variable/ctest_cvs_checkout#variable:CTEST_CVS_CHECKOUT "CTEST_CVS_CHECKOUT") variable) is set, its content is treated as command-line. The command is invoked with the current working directory set to the parent of the source directory, even if the source directory already exists. This can be used to create the source tree from a version control repository.
cmake set_directory_properties set\_directory\_properties
==========================
Set a property of the directory.
```
set_directory_properties(PROPERTIES prop1 value1 prop2 value2)
```
Set a property for the current directory and subdirectories. See [Properties on Directories](../manual/cmake-properties.7#directory-properties) for the list of properties known to CMake.
cmake set_tests_properties set\_tests\_properties
======================
Set a property of the tests.
```
set_tests_properties(test1 [test2...] PROPERTIES prop1 value1 prop2 value2)
```
Set a property for the tests. If the test is not found, CMake will report an error. [`Generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") will be expanded the same as supported by the test’s [`add_test()`](add_test#command:add_test "add_test") call. See [Properties on Tests](../manual/cmake-properties.7#test-properties) for the list of properties known to CMake.
cmake option option
======
Provides an option that the user can optionally select.
```
option(<option_variable> "help string describing option"
[initial value])
```
Provide an option for the user to select as `ON` or `OFF`. If no initial value is provided, `OFF` is used.
If you have options that depend on the values of other options, see the module help for [`CMakeDependentOption`](../module/cmakedependentoption#module:CMakeDependentOption "CMakeDependentOption").
cmake remove remove
======
Deprecated. Use the [`list(REMOVE_ITEM)`](list#command:list "list") command instead.
```
remove(VAR VALUE VALUE ...)
```
Removes `VALUE` from the variable `VAR`. This is typically used to remove entries from a vector (e.g. semicolon separated list). `VALUE` is expanded.
cmake find_program find\_program
=============
A short-hand signature is:
```
find_program (<VAR> name1 [path1 path2 ...])
```
The general signature is:
```
find_program (
<VAR>
name | NAMES name1 [name2 ...] [NAMES_PER_DIR]
[HINTS path1 [path2 ... ENV var]]
[PATHS path1 [path2 ... ENV var]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[DOC "cache documentation string"]
[NO_DEFAULT_PATH]
[NO_CMAKE_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[NO_SYSTEM_ENVIRONMENT_PATH]
[NO_CMAKE_SYSTEM_PATH]
[CMAKE_FIND_ROOT_PATH_BOTH |
ONLY_CMAKE_FIND_ROOT_PATH |
NO_CMAKE_FIND_ROOT_PATH]
)
```
This command is used to find a program. A cache entry named by `<VAR>` is created to store the result of this command. If the program is found the result is stored in the variable and the search will not be repeated unless the variable is cleared. If nothing is found, the result will be `<VAR>-NOTFOUND`, and the search will be attempted again the next time find\_program is invoked with the same variable.
Options include:
`NAMES`
Specify one or more possible names for the program.
When using this to specify names with and without a version suffix, we recommend specifying the unversioned name first so that locally-built packages can be found before those provided by distributions.
`HINTS, PATHS` Specify directories to search in addition to the default locations. The `ENV var` sub-option reads paths from a system environment variable.
`PATH_SUFFIXES` Specify additional subdirectories to check below each directory location otherwise considered.
`DOC` Specify the documentation string for the `<VAR>` cache entry. If `NO_DEFAULT_PATH` is specified, then no additional paths are added to the search. If `NO_DEFAULT_PATH` is not specified, the search process is as follows:
1. Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a `-DVAR=value`. The values are interpreted as [;-lists](../manual/cmake-language.7#cmake-language-lists). This can be skipped if `NO_CMAKE_PATH` is passed.
* `<prefix>/[s]bin` for each `<prefix>` in [`CMAKE_PREFIX_PATH`](../variable/cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH")
* [`CMAKE_PROGRAM_PATH`](../variable/cmake_program_path#variable:CMAKE_PROGRAM_PATH "CMAKE_PROGRAM_PATH")
* [`CMAKE_APPBUNDLE_PATH`](../variable/cmake_appbundle_path#variable:CMAKE_APPBUNDLE_PATH "CMAKE_APPBUNDLE_PATH")
2. Search paths specified in cmake-specific environment variables. These are intended to be set in the user’s shell configuration, and therefore use the host’s native path separator (`;` on Windows and `:` on UNIX). This can be skipped if `NO_CMAKE_ENVIRONMENT_PATH` is passed.
* `<prefix>/[s]bin` for each `<prefix>` in [`CMAKE_PREFIX_PATH`](../variable/cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH")
* [`CMAKE_PROGRAM_PATH`](../variable/cmake_program_path#variable:CMAKE_PROGRAM_PATH "CMAKE_PROGRAM_PATH")
* [`CMAKE_APPBUNDLE_PATH`](../variable/cmake_appbundle_path#variable:CMAKE_APPBUNDLE_PATH "CMAKE_APPBUNDLE_PATH")
3. Search the paths specified by the `HINTS` option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the `PATHS` option.
4. Search the standard system environment variables. This can be skipped if `NO_SYSTEM_ENVIRONMENT_PATH` is an argument.
* `PATH`
5. Search cmake variables defined in the Platform files for the current system. This can be skipped if `NO_CMAKE_SYSTEM_PATH` is passed.
* `<prefix>/[s]bin` for each `<prefix>` in [`CMAKE_SYSTEM_PREFIX_PATH`](../variable/cmake_system_prefix_path#variable:CMAKE_SYSTEM_PREFIX_PATH "CMAKE_SYSTEM_PREFIX_PATH")
* [`CMAKE_SYSTEM_PROGRAM_PATH`](../variable/cmake_system_program_path#variable:CMAKE_SYSTEM_PROGRAM_PATH "CMAKE_SYSTEM_PROGRAM_PATH")
* [`CMAKE_SYSTEM_APPBUNDLE_PATH`](../variable/cmake_system_appbundle_path#variable:CMAKE_SYSTEM_APPBUNDLE_PATH "CMAKE_SYSTEM_APPBUNDLE_PATH")
6. Search the paths specified by the PATHS option or in the short-hand version of the command. These are typically hard-coded guesses.
On OS X the [`CMAKE_FIND_FRAMEWORK`](../variable/cmake_find_framework#variable:CMAKE_FIND_FRAMEWORK "CMAKE_FIND_FRAMEWORK") and [`CMAKE_FIND_APPBUNDLE`](../variable/cmake_find_appbundle#variable:CMAKE_FIND_APPBUNDLE "CMAKE_FIND_APPBUNDLE") variables determine the order of preference between Apple-style and unix-style package components.
The CMake variable [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") specifies one or more directories to be prepended to all other search directories. This effectively “re-roots” the entire search under given locations. Paths which are descendants of the [`CMAKE_STAGING_PREFIX`](../variable/cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX") are excluded from this re-rooting, because that variable is always a path on the host system. By default the [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") is empty.
The [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") variable can also be used to specify exactly one directory to use as a prefix. Setting [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") also has other effects. See the documentation for that variable for more.
These variables are especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") are searched, then the [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") directory is searched, and then the non-rooted directories will be searched. The default behavior can be adjusted by setting [`CMAKE_FIND_ROOT_PATH_MODE_PROGRAM`](../variable/cmake_find_root_path_mode_program#variable:CMAKE_FIND_ROOT_PATH_MODE_PROGRAM "CMAKE_FIND_ROOT_PATH_MODE_PROGRAM"). This behavior can be manually overridden on a per-call basis using options:
`CMAKE_FIND_ROOT_PATH_BOTH` Search in the order described above.
`NO_CMAKE_FIND_ROOT_PATH` Do not use the [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") variable.
`ONLY_CMAKE_FIND_ROOT_PATH` Search only the re-rooted directories and directories below [`CMAKE_STAGING_PREFIX`](../variable/cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX"). The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the `NO_*` options:
```
find_program (<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH)
find_program (<VAR> NAMES name)
```
Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.
When more than one value is given to the `NAMES` option this command by default will consider one name at a time and search every directory for it. The `NAMES_PER_DIR` option tells this command to consider one directory at a time and search for all names in it.
| programming_docs |
cmake use_mangled_mesa use\_mangled\_mesa
==================
Disallowed. See CMake Policy [`CMP0030`](../policy/cmp0030#policy:CMP0030 "CMP0030").
Copy mesa headers for use in combination with system GL.
```
use_mangled_mesa(PATH_TO_MESA OUTPUT_DIRECTORY)
```
The path to mesa includes, should contain gl\_mangle.h. The mesa headers are copied to the specified output directory. This allows mangled mesa headers to override other GL headers by being added to the include directory path earlier.
cmake cmake_host_system_information cmake\_host\_system\_information
================================
Query host system specific information.
```
cmake_host_system_information(RESULT <variable> QUERY <key> ...)
```
Queries system information of the host system on which cmake runs. One or more `<key>` can be provided to select the information to be queried. The list of queried values is stored in `<variable>`.
`<key>` can be one of the following values:
```
NUMBER_OF_LOGICAL_CORES = Number of logical cores.
NUMBER_OF_PHYSICAL_CORES = Number of physical cores.
HOSTNAME = Hostname.
FQDN = Fully qualified domain name.
TOTAL_VIRTUAL_MEMORY = Total virtual memory in megabytes.
AVAILABLE_VIRTUAL_MEMORY = Available virtual memory in megabytes.
TOTAL_PHYSICAL_MEMORY = Total physical memory in megabytes.
AVAILABLE_PHYSICAL_MEMORY = Available physical memory in megabytes.
```
cmake find_file find\_file
==========
A short-hand signature is:
```
find_file (<VAR> name1 [path1 path2 ...])
```
The general signature is:
```
find_file (
<VAR>
name | NAMES name1 [name2 ...]
[HINTS path1 [path2 ... ENV var]]
[PATHS path1 [path2 ... ENV var]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[DOC "cache documentation string"]
[NO_DEFAULT_PATH]
[NO_CMAKE_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[NO_SYSTEM_ENVIRONMENT_PATH]
[NO_CMAKE_SYSTEM_PATH]
[CMAKE_FIND_ROOT_PATH_BOTH |
ONLY_CMAKE_FIND_ROOT_PATH |
NO_CMAKE_FIND_ROOT_PATH]
)
```
This command is used to find a full path to named file. A cache entry named by `<VAR>` is created to store the result of this command. If the full path to a file is found the result is stored in the variable and the search will not be repeated unless the variable is cleared. If nothing is found, the result will be `<VAR>-NOTFOUND`, and the search will be attempted again the next time find\_file is invoked with the same variable.
Options include:
`NAMES`
Specify one or more possible names for the full path to a file.
When using this to specify names with and without a version suffix, we recommend specifying the unversioned name first so that locally-built packages can be found before those provided by distributions.
`HINTS, PATHS` Specify directories to search in addition to the default locations. The `ENV var` sub-option reads paths from a system environment variable.
`PATH_SUFFIXES` Specify additional subdirectories to check below each directory location otherwise considered.
`DOC` Specify the documentation string for the `<VAR>` cache entry. If `NO_DEFAULT_PATH` is specified, then no additional paths are added to the search. If `NO_DEFAULT_PATH` is not specified, the search process is as follows:
1. Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a `-DVAR=value`. The values are interpreted as [;-lists](../manual/cmake-language.7#cmake-language-lists). This can be skipped if `NO_CMAKE_PATH` is passed.
* `<prefix>/include/<arch>` if [`CMAKE_LIBRARY_ARCHITECTURE`](../variable/cmake_library_architecture#variable:CMAKE_LIBRARY_ARCHITECTURE "CMAKE_LIBRARY_ARCHITECTURE") is set, and `<prefix>/include` for each `<prefix>` in [`CMAKE_PREFIX_PATH`](../variable/cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH")
* [`CMAKE_INCLUDE_PATH`](../variable/cmake_include_path#variable:CMAKE_INCLUDE_PATH "CMAKE_INCLUDE_PATH")
* [`CMAKE_FRAMEWORK_PATH`](../variable/cmake_framework_path#variable:CMAKE_FRAMEWORK_PATH "CMAKE_FRAMEWORK_PATH")
2. Search paths specified in cmake-specific environment variables. These are intended to be set in the user’s shell configuration, and therefore use the host’s native path separator (`;` on Windows and `:` on UNIX). This can be skipped if `NO_CMAKE_ENVIRONMENT_PATH` is passed.
* `<prefix>/include/<arch>` if [`CMAKE_LIBRARY_ARCHITECTURE`](../variable/cmake_library_architecture#variable:CMAKE_LIBRARY_ARCHITECTURE "CMAKE_LIBRARY_ARCHITECTURE") is set, and `<prefix>/include` for each `<prefix>` in [`CMAKE_PREFIX_PATH`](../variable/cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH")
* [`CMAKE_INCLUDE_PATH`](../variable/cmake_include_path#variable:CMAKE_INCLUDE_PATH "CMAKE_INCLUDE_PATH")
* [`CMAKE_FRAMEWORK_PATH`](../variable/cmake_framework_path#variable:CMAKE_FRAMEWORK_PATH "CMAKE_FRAMEWORK_PATH")
3. Search the paths specified by the `HINTS` option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the `PATHS` option.
4. Search the standard system environment variables. This can be skipped if `NO_SYSTEM_ENVIRONMENT_PATH` is an argument.
* Directories in `INCLUDE`. On Windows hosts: `<prefix>/include/<arch>` if [`CMAKE_LIBRARY_ARCHITECTURE`](../variable/cmake_library_architecture#variable:CMAKE_LIBRARY_ARCHITECTURE "CMAKE_LIBRARY_ARCHITECTURE") is set, and `<prefix>/include` for each `<prefix>/[s]bin` in `PATH`, and `<entry>/include` for other entries in `PATH`, and the directories in `PATH` itself.
5. Search cmake variables defined in the Platform files for the current system. This can be skipped if `NO_CMAKE_SYSTEM_PATH` is passed.
* `<prefix>/include/<arch>` if [`CMAKE_LIBRARY_ARCHITECTURE`](../variable/cmake_library_architecture#variable:CMAKE_LIBRARY_ARCHITECTURE "CMAKE_LIBRARY_ARCHITECTURE") is set, and `<prefix>/include` for each `<prefix>` in [`CMAKE_SYSTEM_PREFIX_PATH`](../variable/cmake_system_prefix_path#variable:CMAKE_SYSTEM_PREFIX_PATH "CMAKE_SYSTEM_PREFIX_PATH")
* [`CMAKE_SYSTEM_INCLUDE_PATH`](../variable/cmake_system_include_path#variable:CMAKE_SYSTEM_INCLUDE_PATH "CMAKE_SYSTEM_INCLUDE_PATH")
* [`CMAKE_SYSTEM_FRAMEWORK_PATH`](../variable/cmake_system_framework_path#variable:CMAKE_SYSTEM_FRAMEWORK_PATH "CMAKE_SYSTEM_FRAMEWORK_PATH")
6. Search the paths specified by the PATHS option or in the short-hand version of the command. These are typically hard-coded guesses.
On OS X the [`CMAKE_FIND_FRAMEWORK`](../variable/cmake_find_framework#variable:CMAKE_FIND_FRAMEWORK "CMAKE_FIND_FRAMEWORK") and [`CMAKE_FIND_APPBUNDLE`](../variable/cmake_find_appbundle#variable:CMAKE_FIND_APPBUNDLE "CMAKE_FIND_APPBUNDLE") variables determine the order of preference between Apple-style and unix-style package components.
The CMake variable [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") specifies one or more directories to be prepended to all other search directories. This effectively “re-roots” the entire search under given locations. Paths which are descendants of the [`CMAKE_STAGING_PREFIX`](../variable/cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX") are excluded from this re-rooting, because that variable is always a path on the host system. By default the [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") is empty.
The [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") variable can also be used to specify exactly one directory to use as a prefix. Setting [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") also has other effects. See the documentation for that variable for more.
These variables are especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") are searched, then the [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") directory is searched, and then the non-rooted directories will be searched. The default behavior can be adjusted by setting [`CMAKE_FIND_ROOT_PATH_MODE_INCLUDE`](../variable/cmake_find_root_path_mode_include#variable:CMAKE_FIND_ROOT_PATH_MODE_INCLUDE "CMAKE_FIND_ROOT_PATH_MODE_INCLUDE"). This behavior can be manually overridden on a per-call basis using options:
`CMAKE_FIND_ROOT_PATH_BOTH` Search in the order described above.
`NO_CMAKE_FIND_ROOT_PATH` Do not use the [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") variable.
`ONLY_CMAKE_FIND_ROOT_PATH` Search only the re-rooted directories and directories below [`CMAKE_STAGING_PREFIX`](../variable/cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX"). The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the `NO_*` options:
```
find_file (<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH)
find_file (<VAR> NAMES name)
```
Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.
cmake target_compile_options target\_compile\_options
========================
Add compile options to a target.
```
target_compile_options(<target> [BEFORE]
<INTERFACE|PUBLIC|PRIVATE> [items1...]
[<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
```
Specify compile options to use when compiling a given target. The named `<target>` must have been created by a command such as [`add_executable()`](add_executable#command:add_executable "add_executable") or [`add_library()`](add_library#command:add_library "add_library") and must not be an [IMPORTED Target](../manual/cmake-buildsystem.7#imported-targets). If `BEFORE` is specified, the content will be prepended to the property instead of being appended.
This command can be used to add any options, but alternative commands exist to add preprocessor definitions ([`target_compile_definitions()`](target_compile_definitions#command:target_compile_definitions "target_compile_definitions") and [`add_definitions()`](add_definitions#command:add_definitions "add_definitions")) or include directories ([`target_include_directories()`](target_include_directories#command:target_include_directories "target_include_directories") and [`include_directories()`](include_directories#command:include_directories "include_directories")). See documentation of the [`directory`](../prop_dir/compile_options#prop_dir:COMPILE_OPTIONS "COMPILE_OPTIONS") and [`target`](../prop_tgt/compile_options#prop_tgt:COMPILE_OPTIONS "COMPILE_OPTIONS") `COMPILE_OPTIONS` properties.
The `INTERFACE`, `PUBLIC` and `PRIVATE` keywords are required to specify the scope of the following arguments. `PRIVATE` and `PUBLIC` items will populate the [`COMPILE_OPTIONS`](../prop_tgt/compile_options#prop_tgt:COMPILE_OPTIONS "COMPILE_OPTIONS") property of `<target>`. `PUBLIC` and `INTERFACE` items will populate the [`INTERFACE_COMPILE_OPTIONS`](../prop_tgt/interface_compile_options#prop_tgt:INTERFACE_COMPILE_OPTIONS "INTERFACE_COMPILE_OPTIONS") property of `<target>`. The following arguments specify compile options. Repeated calls for the same `<target>` append items in the order called.
Arguments to `target_compile_options` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake install_targets install\_targets
================
Deprecated. Use the [`install(TARGETS)`](install#command:install "install") command instead.
This command has been superceded by the [`install()`](install#command:install "install") command. It is provided for compatibility with older CMake code.
```
install_targets(<dir> [RUNTIME_DIRECTORY dir] target target)
```
Create rules to install the listed targets into the given directory. The directory `<dir>` is relative to the installation prefix, which is stored in the variable [`CMAKE_INSTALL_PREFIX`](../variable/cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX"). If `RUNTIME_DIRECTORY` is specified, then on systems with special runtime files (Windows DLL), the files will be copied to that directory.
cmake add_test add\_test
=========
Add a test to the project to be run by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)").
```
add_test(NAME <name> COMMAND <command> [<arg>...]
[CONFIGURATIONS <config>...]
[WORKING_DIRECTORY <dir>])
```
Add a test called `<name>`. The test name may not contain spaces, quotes, or other characters special in CMake syntax. The options are:
`COMMAND` Specify the test command-line. If `<command>` specifies an executable target (created by [`add_executable()`](add_executable#command:add_executable "add_executable")) it will automatically be replaced by the location of the executable created at build time.
`CONFIGURATIONS` Restrict execution of the test only to the named configurations.
`WORKING_DIRECTORY` Set the [`WORKING_DIRECTORY`](../prop_test/working_directory#prop_test:WORKING_DIRECTORY "WORKING_DIRECTORY") test property to specify the working directory in which to execute the test. If not specified the test will be run with the current working directory set to the build directory corresponding to the current source directory. The given test command is expected to exit with code `0` to pass and non-zero to fail, or vice-versa if the [`WILL_FAIL`](../prop_test/will_fail#prop_test:WILL_FAIL "WILL_FAIL") test property is set. Any output written to stdout or stderr will be captured by [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)") but does not affect the pass/fail status unless the [`PASS_REGULAR_EXPRESSION`](../prop_test/pass_regular_expression#prop_test:PASS_REGULAR_EXPRESSION "PASS_REGULAR_EXPRESSION") or [`FAIL_REGULAR_EXPRESSION`](../prop_test/fail_regular_expression#prop_test:FAIL_REGULAR_EXPRESSION "FAIL_REGULAR_EXPRESSION") test property is used.
The `COMMAND` and `WORKING_DIRECTORY` options may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions.
Example usage:
```
add_test(NAME mytest
COMMAND testDriver --config $<CONFIGURATION>
--exe $<TARGET_FILE:myexe>)
```
This creates a test `mytest` whose command runs a `testDriver` tool passing the configuration name and the full path to the executable file produced by target `myexe`.
Note
CMake will generate tests only if the [`enable_testing()`](enable_testing#command:enable_testing "enable_testing") command has been invoked. The [`CTest`](../module/ctest#module:CTest "CTest") module invokes the command automatically when the `BUILD_TESTING` option is `ON`.
```
add_test(<name> <command> [<arg>...])
```
Add a test called `<name>` with the given command-line. Unlike the above `NAME` signature no transformation is performed on the command-line to support target names or generator expressions.
cmake ctest_upload ctest\_upload
=============
Upload files to a dashboard server as a [Dashboard Client](../manual/ctest.1#dashboard-client).
```
ctest_upload(FILES <file>... [QUIET] [CAPTURE_CMAKE_ERROR <result-var>])
```
The options are:
`FILES <file>...` Specify a list of files to be sent along with the build results to the dashboard server.
`QUIET` Suppress any CTest-specific non-error output that would have been printed to the console otherwise.
`CAPTURE_CMAKE_ERROR <result-var>` Store in the `<result-var>` variable -1 if there are any errors running the command and prevent ctest from returning non-zero if an error occurs.
cmake add_custom_command add\_custom\_command
====================
Add a custom build rule to the generated build system.
There are two main signatures for `add_custom_command`.
Generating Files
----------------
The first signature is for adding a custom command to produce an output:
```
add_custom_command(OUTPUT output1 [output2 ...]
COMMAND command1 [ARGS] [args1...]
[COMMAND command2 [ARGS] [args2...] ...]
[MAIN_DEPENDENCY depend]
[DEPENDS [depends...]]
[BYPRODUCTS [files...]]
[IMPLICIT_DEPENDS <lang1> depend1
[<lang2> depend2] ...]
[WORKING_DIRECTORY dir]
[COMMENT comment]
[DEPFILE depfile]
[VERBATIM] [APPEND] [USES_TERMINAL]
[COMMAND_EXPAND_LISTS])
```
This defines a command to generate specified `OUTPUT` file(s). A target created in the same directory (`CMakeLists.txt` file) that specifies any output of the custom command as a source file is given a rule to generate the file using the command at build time. Do not list the output in more than one independent target that may build in parallel or the two instances of the rule may conflict (instead use the [`add_custom_target()`](add_custom_target#command:add_custom_target "add_custom_target") command to drive the command and make the other targets depend on that one). In makefile terms this creates a new target in the following form:
```
OUTPUT: MAIN_DEPENDENCY DEPENDS
COMMAND
```
The options are:
`APPEND` Append the `COMMAND` and `DEPENDS` option values to the custom command for the first output specified. There must have already been a previous call to this command with the same output. The `COMMENT`, `MAIN_DEPENDENCY`, and `WORKING_DIRECTORY` options are currently ignored when APPEND is given, but may be used in the future.
`BYPRODUCTS`
Specify the files the command is expected to produce but whose modification time may or may not be newer than the dependencies. If a byproduct name is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory. Each byproduct file will be marked with the [`GENERATED`](../prop_sf/generated#prop_sf:GENERATED "GENERATED") source file property automatically.
Explicit specification of byproducts is supported by the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator to tell the `ninja` build tool how to regenerate byproducts when they are missing. It is also useful when other build rules (e.g. custom commands) depend on the byproducts. Ninja requires a build rule for any generated file on which another rule depends even if there are order-only dependencies to ensure the byproducts will be available before their dependents build.
The `BYPRODUCTS` option is ignored on non-Ninja generators except to mark byproducts `GENERATED`.
`COMMAND`
Specify the command-line(s) to execute at build time. If more than one `COMMAND` is specified they will be executed in order, but *not* necessarily composed into a stateful shell or batch script. (To run a full script, use the [`configure_file()`](configure_file#command:configure_file "configure_file") command or the [`file(GENERATE)`](file#command:file "file") command to create it, and then specify a `COMMAND` to launch it.) The optional `ARGS` argument is for backward compatibility and will be ignored.
If `COMMAND` specifies an executable target name (created by the [`add_executable()`](add_executable#command:add_executable "add_executable") command) it will automatically be replaced by the location of the executable created at build time. If set, the [`CROSSCOMPILING_EMULATOR`](../prop_tgt/crosscompiling_emulator#prop_tgt:CROSSCOMPILING_EMULATOR "CROSSCOMPILING_EMULATOR") executable target property will also be prepended to the command to allow the executable to run on the host. (Use the `TARGET_FILE` [`generator expression`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") to reference an executable later in the command line.) Additionally a target-level dependency will be added so that the executable target will be built before any target using this custom command. However this does NOT add a file-level dependency that would cause the custom command to re-run whenever the executable is recompiled.
Arguments to `COMMAND` may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)"). References to target names in generator expressions imply target-level dependencies, but NOT file-level dependencies. List target names with the `DEPENDS` option to add file-level dependencies.
`COMMENT` Display the given message before the commands are executed at build time.
`DEPENDS`
Specify files on which the command depends. If any dependency is an `OUTPUT` of another custom command in the same directory (`CMakeLists.txt` file) CMake automatically brings the other custom command into the target in which this command is built. If `DEPENDS` is not specified the command will run whenever the `OUTPUT` is missing; if the command does not actually create the `OUTPUT` then the rule will always run. If `DEPENDS` specifies any target (created by the [`add_custom_target()`](add_custom_target#command:add_custom_target "add_custom_target"), [`add_executable()`](add_executable#command:add_executable "add_executable"), or [`add_library()`](add_library#command:add_library "add_library") command) a target-level dependency is created to make sure the target is built before any target using this custom command. Additionally, if the target is an executable or library a file-level dependency is created to cause the custom command to re-run whenever the target is recompiled.
Arguments to `DEPENDS` may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)").
`COMMAND_EXPAND_LISTS` Lists in `COMMAND` arguments will be expanded, including those created with [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)"), allowing `COMMAND` arguments such as `${CC} "-I$<JOIN:$<TARGET_PROPERTY:foo,INCLUDE_DIRECTORIES>,;-I>" foo.cc` to be properly expanded.
`IMPLICIT_DEPENDS` Request scanning of implicit dependencies of an input file. The language given specifies the programming language whose corresponding dependency scanner should be used. Currently only `C` and `CXX` language scanners are supported. The language has to be specified for every file in the `IMPLICIT_DEPENDS` list. Dependencies discovered from the scanning are added to those of the custom command at build time. Note that the `IMPLICIT_DEPENDS` option is currently supported only for Makefile generators and will be ignored by other generators.
`MAIN_DEPENDENCY` Specify the primary input source file to the command. This is treated just like any value given to the `DEPENDS` option but also suggests to Visual Studio generators where to hang the custom command. At most one custom command may specify a given source file as its main dependency.
`OUTPUT` Specify the output files the command is expected to produce. If an output name is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory. Each output file will be marked with the [`GENERATED`](../prop_sf/generated#prop_sf:GENERATED "GENERATED") source file property automatically. If the output of the custom command is not actually created as a file on disk it should be marked with the [`SYMBOLIC`](../prop_sf/symbolic#prop_sf:SYMBOLIC "SYMBOLIC") source file property.
`USES_TERMINAL` The command will be given direct access to the terminal if possible. With the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator, this places the command in the `console` [`pool`](../prop_gbl/job_pools#prop_gbl:JOB_POOLS "JOB_POOLS").
`VERBATIM` All arguments to the commands will be escaped properly for the build tool so that the invoked command receives each argument unchanged. Note that one level of escapes is still used by the CMake language processor before add\_custom\_command even sees the arguments. Use of `VERBATIM` is recommended as it enables correct behavior. When `VERBATIM` is not given the behavior is platform specific because there is no protection of tool-specific special characters.
`WORKING_DIRECTORY` Execute the command with the given current working directory. If it is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory.
`DEPFILE` Specify a `.d` depfile for the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator. A `.d` file holds dependencies usually emitted by the custom command itself. Using `DEPFILE` with other generators than Ninja is an error. Build Events
------------
The second signature adds a custom command to a target such as a library or executable. This is useful for performing an operation before or after building the target. The command becomes part of the target and will only execute when the target itself is built. If the target is already built, the command will not execute.
```
add_custom_command(TARGET <target>
PRE_BUILD | PRE_LINK | POST_BUILD
COMMAND command1 [ARGS] [args1...]
[COMMAND command2 [ARGS] [args2...] ...]
[BYPRODUCTS [files...]]
[WORKING_DIRECTORY dir]
[COMMENT comment]
[VERBATIM] [USES_TERMINAL])
```
This defines a new command that will be associated with building the specified `<target>`. The `<target>` must be defined in the current directory; targets defined in other directories may not be specified.
When the command will happen is determined by which of the following is specified:
`PRE_BUILD` Run before any other rules are executed within the target. This is supported only on Visual Studio 8 or later. For all other generators `PRE_BUILD` will be treated as `PRE_LINK`.
`PRE_LINK` Run after sources have been compiled but before linking the binary or running the librarian or archiver tool of a static library. This is not defined for targets created by the [`add_custom_target()`](add_custom_target#command:add_custom_target "add_custom_target") command.
`POST_BUILD` Run after all other rules within the target have been executed.
| programming_docs |
cmake build_command build\_command
==============
Get a command line to build the current project. This is mainly intended for internal use by the [`CTest`](../module/ctest#module:CTest "CTest") module.
```
build_command(<variable>
[CONFIGURATION <config>]
[TARGET <target>]
[PROJECT_NAME <projname>] # legacy, causes warning
)
```
Sets the given `<variable>` to a command-line string of the form:
```
<cmake> --build . [--config <config>] [--target <target>] [-- -i]
```
where `<cmake>` is the location of the [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") command-line tool, and `<config>` and `<target>` are the values provided to the `CONFIGURATION` and `TARGET` options, if any. The trailing `-- -i` option is added for [Makefile Generators](../manual/cmake-generators.7#makefile-generators) if policy [`CMP0061`](../policy/cmp0061#policy:CMP0061 "CMP0061") is not set to `NEW`.
When invoked, this `cmake --build` command line will launch the underlying build system tool.
```
build_command(<cachevariable> <makecommand>)
```
This second signature is deprecated, but still available for backwards compatibility. Use the first signature instead.
It sets the given `<cachevariable>` to a command-line string as above but without the `--target` option. The `<makecommand>` is ignored but should be the full path to devenv, nmake, make or one of the end user build tools for legacy invocations.
Note
In CMake versions prior to 3.0 this command returned a command line that directly invokes the native build tool for the current generator. Their implementation of the `PROJECT_NAME` option had no useful effects, so CMake now warns on use of the option.
cmake string string
======
* [Search and Replace](#search-and-replace)
+ [FIND](#find)
+ [REPLACE](#replace)
* [Regular Expressions](#regular-expressions)
+ [REGEX MATCH](#regex-match)
+ [REGEX MATCHALL](#regex-matchall)
+ [REGEX REPLACE](#regex-replace)
+ [Regex Specification](#regex-specification)
* [Manipulation](#manipulation)
+ [APPEND](#append)
+ [CONCAT](#concat)
+ [TOLOWER](#tolower)
+ [TOUPPER](#toupper)
+ [LENGTH](#length)
+ [SUBSTRING](#substring)
+ [STRIP](#strip)
+ [GENEX\_STRIP](#genex-strip)
* [Comparison](#comparison)
* [Hashing](#hashing)
* [Generation](#generation)
+ [ASCII](#ascii)
+ [CONFIGURE](#configure)
+ [RANDOM](#random)
+ [TIMESTAMP](#timestamp)
+ [UUID](#uuid)
String operations.
Search and Replace
------------------
### FIND
```
string(FIND <string> <substring> <output variable> [REVERSE])
```
Return the position where the given substring was found in the supplied string. If the `REVERSE` flag was used, the command will search for the position of the last occurrence of the specified substring. If the substring is not found, a position of -1 is returned.
### REPLACE
```
string(REPLACE <match_string>
<replace_string> <output variable>
<input> [<input>...])
```
Replace all occurrences of `match_string` in the input with `replace_string` and store the result in the output.
Regular Expressions
-------------------
### REGEX MATCH
```
string(REGEX MATCH <regular_expression>
<output variable> <input> [<input>...])
```
Match the regular expression once and store the match in the output variable. All `<input>` arguments are concatenated before matching.
### REGEX MATCHALL
```
string(REGEX MATCHALL <regular_expression>
<output variable> <input> [<input>...])
```
Match the regular expression as many times as possible and store the matches in the output variable as a list. All `<input>` arguments are concatenated before matching.
### REGEX REPLACE
```
string(REGEX REPLACE <regular_expression>
<replace_expression> <output variable>
<input> [<input>...])
```
Match the regular expression as many times as possible and substitute the replacement expression for the match in the output. All `<input>` arguments are concatenated before matching.
The replace expression may refer to paren-delimited subexpressions of the match using `\1`, `\2`, …, `\9`. Note that two backslashes (`\\1`) are required in CMake code to get a backslash through argument parsing.
### Regex Specification
The following characters have special meaning in regular expressions:
`^` Matches at beginning of input
`$` Matches at end of input
`.` Matches any single character
`[ ]` Matches any character(s) inside the brackets
`[^ ]` Matches any character(s) not inside the brackets
`-` Inside brackets, specifies an inclusive range between characters on either side e.g. `[a-f]` is `[abcdef]` To match a literal `-` using brackets, make it the first or the last character e.g. `[+*/-]` matches basic mathematical operators.
`*` Matches preceding pattern zero or more times
`+` Matches preceding pattern one or more times
`?` Matches preceding pattern zero or once only
`|` Matches a pattern on either side of the `|`
`()` Saves a matched subexpression, which can be referenced in the `REGEX REPLACE` operation. Additionally it is saved by all regular expression-related commands, including e.g. [`if(MATCHES)`](if#command:if "if"), in the variables [`CMAKE_MATCH_<n>`](# "CMAKE_MATCH_<n>") for `<n>` 0..9. `*`, `+` and `?` have higher precedence than concatenation. `|` has lower precedence than concatenation. This means that the regular expression `^ab+d$` matches `abbd` but not `ababd`, and the regular expression `^(ab|cd)$` matches `ab` but not `abd`.
Manipulation
------------
### APPEND
```
string(APPEND <string variable> [<input>...])
```
Append all the input arguments to the string.
### CONCAT
```
string(CONCAT <output variable> [<input>...])
```
Concatenate all the input arguments together and store the result in the named output variable.
### TOLOWER
```
string(TOLOWER <string1> <output variable>)
```
Convert string to lower characters.
### TOUPPER
```
string(TOUPPER <string1> <output variable>)
```
Convert string to upper characters.
### LENGTH
```
string(LENGTH <string> <output variable>)
```
Store in an output variable a given string’s length.
### SUBSTRING
```
string(SUBSTRING <string> <begin> <length> <output variable>)
```
Store in an output variable a substring of a given string. If length is `-1` the remainder of the string starting at begin will be returned. If string is shorter than length then end of string is used instead.
Note
CMake 3.1 and below reported an error if length pointed past the end of string.
### STRIP
```
string(STRIP <string> <output variable>)
```
Store in an output variable a substring of a given string with leading and trailing spaces removed.
### GENEX\_STRIP
```
string(GENEX_STRIP <input string> <output variable>)
```
Strip any [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") from the `input string` and store the result in the `output variable`.
Comparison
----------
```
string(COMPARE LESS <string1> <string2> <output variable>)
string(COMPARE GREATER <string1> <string2> <output variable>)
string(COMPARE EQUAL <string1> <string2> <output variable>)
string(COMPARE NOTEQUAL <string1> <string2> <output variable>)
string(COMPARE LESS_EQUAL <string1> <string2> <output variable>)
string(COMPARE GREATER_EQUAL <string1> <string2> <output variable>)
```
Compare the strings and store true or false in the output variable.
Hashing
-------
```
string(<HASH> <output variable> <input>)
```
Compute a cryptographic hash of the input string. The supported `<HASH>` algorithm names are:
`MD5` Message-Digest Algorithm 5, RFC 1321.
`SHA1` US Secure Hash Algorithm 1, RFC 3174.
`SHA224` US Secure Hash Algorithms, RFC 4634.
`SHA256` US Secure Hash Algorithms, RFC 4634.
`SHA384` US Secure Hash Algorithms, RFC 4634.
`SHA512` US Secure Hash Algorithms, RFC 4634.
`SHA3_224` Keccak SHA-3.
`SHA3_256` Keccak SHA-3.
`SHA3_384` Keccak SHA-3.
`SHA3_512` Keccak SHA-3. Generation
----------
### ASCII
```
string(ASCII <number> [<number> ...] <output variable>)
```
Convert all numbers into corresponding ASCII characters.
### CONFIGURE
```
string(CONFIGURE <string1> <output variable>
[@ONLY] [ESCAPE_QUOTES])
```
Transform a string like [`configure_file()`](configure_file#command:configure_file "configure_file") transforms a file.
### RANDOM
```
string(RANDOM [LENGTH <length>] [ALPHABET <alphabet>]
[RANDOM_SEED <seed>] <output variable>)
```
Return a random string of given length consisting of characters from the given alphabet. Default length is 5 characters and default alphabet is all numbers and upper and lower case letters. If an integer `RANDOM_SEED` is given, its value will be used to seed the random number generator.
### TIMESTAMP
```
string(TIMESTAMP <output variable> [<format string>] [UTC])
```
Write a string representation of the current date and/or time to the output variable.
Should the command be unable to obtain a timestamp the output variable will be set to the empty string “”.
The optional `UTC` flag requests the current date/time representation to be in Coordinated Universal Time (UTC) rather than local time.
The optional `<format string>` may contain the following format specifiers:
```
%% A literal percent sign (%).
%d The day of the current month (01-31).
%H The hour on a 24-hour clock (00-23).
%I The hour on a 12-hour clock (01-12).
%j The day of the current year (001-366).
%m The month of the current year (01-12).
%b Abbreviated month name (e.g. Oct).
%M The minute of the current hour (00-59).
%s Seconds since midnight (UTC) 1-Jan-1970 (UNIX time).
%S The second of the current minute.
60 represents a leap second. (00-60)
%U The week number of the current year (00-53).
%w The day of the current week. 0 is Sunday. (0-6)
%a Abbreviated weekday name (e.g. Fri).
%y The last two digits of the current year (00-99)
%Y The current year.
```
Unknown format specifiers will be ignored and copied to the output as-is.
If no explicit `<format string>` is given it will default to:
```
%Y-%m-%dT%H:%M:%S for local time.
%Y-%m-%dT%H:%M:%SZ for UTC.
```
```
string(MAKE_C_IDENTIFIER <input string> <output variable>)
```
Write a string which can be used as an identifier in C.
Note
If the `SOURCE_DATE_EPOCH` environment variable is set, its value will be used instead of the current time. See <https://reproducible-builds.org/specs/source-date-epoch/> for details.
### UUID
```
string(UUID <output variable> NAMESPACE <namespace> NAME <name>
TYPE <MD5|SHA1> [UPPER])
```
Create a univerally unique identifier (aka GUID) as per RFC4122 based on the hash of the combined values of `<namespace>` (which itself has to be a valid UUID) and `<name>`. The hash algorithm can be either `MD5` (Version 3 UUID) or `SHA1` (Version 5 UUID). A UUID has the format `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` where each `x` represents a lower case hexadecimal character. Where required an uppercase representation can be requested with the optional `UPPER` flag.
cmake enable_language enable\_language
================
Enable a language (CXX/C/Fortran/etc)
```
enable_language(<lang> [OPTIONAL] )
```
This command enables support for the named language in CMake. This is the same as the project command but does not create any of the extra variables that are created by the project command. Example languages are CXX, C, Fortran.
This command must be called in file scope, not in a function call. Furthermore, it must be called in the highest directory common to all targets using the named language directly for compiling sources or indirectly through link dependencies. It is simplest to enable all needed languages in the top-level directory of a project.
The `OPTIONAL` keyword is a placeholder for future implementation and does not currently work.
cmake find_library find\_library
=============
A short-hand signature is:
```
find_library (<VAR> name1 [path1 path2 ...])
```
The general signature is:
```
find_library (
<VAR>
name | NAMES name1 [name2 ...] [NAMES_PER_DIR]
[HINTS path1 [path2 ... ENV var]]
[PATHS path1 [path2 ... ENV var]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[DOC "cache documentation string"]
[NO_DEFAULT_PATH]
[NO_CMAKE_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[NO_SYSTEM_ENVIRONMENT_PATH]
[NO_CMAKE_SYSTEM_PATH]
[CMAKE_FIND_ROOT_PATH_BOTH |
ONLY_CMAKE_FIND_ROOT_PATH |
NO_CMAKE_FIND_ROOT_PATH]
)
```
This command is used to find a library. A cache entry named by `<VAR>` is created to store the result of this command. If the library is found the result is stored in the variable and the search will not be repeated unless the variable is cleared. If nothing is found, the result will be `<VAR>-NOTFOUND`, and the search will be attempted again the next time find\_library is invoked with the same variable.
Options include:
`NAMES`
Specify one or more possible names for the library.
When using this to specify names with and without a version suffix, we recommend specifying the unversioned name first so that locally-built packages can be found before those provided by distributions.
`HINTS, PATHS` Specify directories to search in addition to the default locations. The `ENV var` sub-option reads paths from a system environment variable.
`PATH_SUFFIXES` Specify additional subdirectories to check below each directory location otherwise considered.
`DOC` Specify the documentation string for the `<VAR>` cache entry. If `NO_DEFAULT_PATH` is specified, then no additional paths are added to the search. If `NO_DEFAULT_PATH` is not specified, the search process is as follows:
1. Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a `-DVAR=value`. The values are interpreted as [;-lists](../manual/cmake-language.7#cmake-language-lists). This can be skipped if `NO_CMAKE_PATH` is passed.
* `<prefix>/lib/<arch>` if [`CMAKE_LIBRARY_ARCHITECTURE`](../variable/cmake_library_architecture#variable:CMAKE_LIBRARY_ARCHITECTURE "CMAKE_LIBRARY_ARCHITECTURE") is set, and `<prefix>/lib` for each `<prefix>` in [`CMAKE_PREFIX_PATH`](../variable/cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH")
* [`CMAKE_LIBRARY_PATH`](../variable/cmake_library_path#variable:CMAKE_LIBRARY_PATH "CMAKE_LIBRARY_PATH")
* [`CMAKE_FRAMEWORK_PATH`](../variable/cmake_framework_path#variable:CMAKE_FRAMEWORK_PATH "CMAKE_FRAMEWORK_PATH")
2. Search paths specified in cmake-specific environment variables. These are intended to be set in the user’s shell configuration, and therefore use the host’s native path separator (`;` on Windows and `:` on UNIX). This can be skipped if `NO_CMAKE_ENVIRONMENT_PATH` is passed.
* `<prefix>/lib/<arch>` if [`CMAKE_LIBRARY_ARCHITECTURE`](../variable/cmake_library_architecture#variable:CMAKE_LIBRARY_ARCHITECTURE "CMAKE_LIBRARY_ARCHITECTURE") is set, and `<prefix>/lib` for each `<prefix>` in [`CMAKE_PREFIX_PATH`](../variable/cmake_prefix_path#variable:CMAKE_PREFIX_PATH "CMAKE_PREFIX_PATH")
* [`CMAKE_LIBRARY_PATH`](../variable/cmake_library_path#variable:CMAKE_LIBRARY_PATH "CMAKE_LIBRARY_PATH")
* [`CMAKE_FRAMEWORK_PATH`](../variable/cmake_framework_path#variable:CMAKE_FRAMEWORK_PATH "CMAKE_FRAMEWORK_PATH")
3. Search the paths specified by the `HINTS` option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the `PATHS` option.
4. Search the standard system environment variables. This can be skipped if `NO_SYSTEM_ENVIRONMENT_PATH` is an argument.
* Directories in `LIB`. On Windows hosts: `<prefix>/lib/<arch>` if [`CMAKE_LIBRARY_ARCHITECTURE`](../variable/cmake_library_architecture#variable:CMAKE_LIBRARY_ARCHITECTURE "CMAKE_LIBRARY_ARCHITECTURE") is set, and `<prefix>/lib` for each `<prefix>/[s]bin` in `PATH`, and `<entry>/lib` for other entries in `PATH`, and the directories in `PATH` itself.
5. Search cmake variables defined in the Platform files for the current system. This can be skipped if `NO_CMAKE_SYSTEM_PATH` is passed.
* `<prefix>/lib/<arch>` if [`CMAKE_LIBRARY_ARCHITECTURE`](../variable/cmake_library_architecture#variable:CMAKE_LIBRARY_ARCHITECTURE "CMAKE_LIBRARY_ARCHITECTURE") is set, and `<prefix>/lib` for each `<prefix>` in [`CMAKE_SYSTEM_PREFIX_PATH`](../variable/cmake_system_prefix_path#variable:CMAKE_SYSTEM_PREFIX_PATH "CMAKE_SYSTEM_PREFIX_PATH")
* [`CMAKE_SYSTEM_LIBRARY_PATH`](../variable/cmake_system_library_path#variable:CMAKE_SYSTEM_LIBRARY_PATH "CMAKE_SYSTEM_LIBRARY_PATH")
* [`CMAKE_SYSTEM_FRAMEWORK_PATH`](../variable/cmake_system_framework_path#variable:CMAKE_SYSTEM_FRAMEWORK_PATH "CMAKE_SYSTEM_FRAMEWORK_PATH")
6. Search the paths specified by the PATHS option or in the short-hand version of the command. These are typically hard-coded guesses.
On OS X the [`CMAKE_FIND_FRAMEWORK`](../variable/cmake_find_framework#variable:CMAKE_FIND_FRAMEWORK "CMAKE_FIND_FRAMEWORK") and [`CMAKE_FIND_APPBUNDLE`](../variable/cmake_find_appbundle#variable:CMAKE_FIND_APPBUNDLE "CMAKE_FIND_APPBUNDLE") variables determine the order of preference between Apple-style and unix-style package components.
The CMake variable [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") specifies one or more directories to be prepended to all other search directories. This effectively “re-roots” the entire search under given locations. Paths which are descendants of the [`CMAKE_STAGING_PREFIX`](../variable/cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX") are excluded from this re-rooting, because that variable is always a path on the host system. By default the [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") is empty.
The [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") variable can also be used to specify exactly one directory to use as a prefix. Setting [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") also has other effects. See the documentation for that variable for more.
These variables are especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") are searched, then the [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") directory is searched, and then the non-rooted directories will be searched. The default behavior can be adjusted by setting [`CMAKE_FIND_ROOT_PATH_MODE_LIBRARY`](../variable/cmake_find_root_path_mode_library#variable:CMAKE_FIND_ROOT_PATH_MODE_LIBRARY "CMAKE_FIND_ROOT_PATH_MODE_LIBRARY"). This behavior can be manually overridden on a per-call basis using options:
`CMAKE_FIND_ROOT_PATH_BOTH` Search in the order described above.
`NO_CMAKE_FIND_ROOT_PATH` Do not use the [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") variable.
`ONLY_CMAKE_FIND_ROOT_PATH` Search only the re-rooted directories and directories below [`CMAKE_STAGING_PREFIX`](../variable/cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX"). The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the `NO_*` options:
```
find_library (<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH)
find_library (<VAR> NAMES name)
```
Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.
When more than one value is given to the `NAMES` option this command by default will consider one name at a time and search every directory for it. The `NAMES_PER_DIR` option tells this command to consider one directory at a time and search for all names in it.
Each library name given to the `NAMES` option is first considered as a library file name and then considered with platform-specific prefixes (e.g. `lib`) and suffixes (e.g. `.so`). Therefore one may specify library file names such as `libfoo.a` directly. This can be used to locate static libraries on UNIX-like systems.
If the library found is a framework, then `<VAR>` will be set to the full path to the framework `<fullPath>/A.framework`. When a full path to a framework is used as a library, CMake will use a `-framework A`, and a `-F<fullPath>` to link the framework to the target.
If the [`CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX`](../variable/cmake_find_library_custom_lib_suffix#variable:CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX "CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX") variable is set all search paths will be tested as normal, with the suffix appended, and with all matches of `lib/` replaced with `lib${CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX}/`. This variable overrides the [`FIND_LIBRARY_USE_LIB32_PATHS`](../prop_gbl/find_library_use_lib32_paths#prop_gbl:FIND_LIBRARY_USE_LIB32_PATHS "FIND_LIBRARY_USE_LIB32_PATHS"), [`FIND_LIBRARY_USE_LIBX32_PATHS`](../prop_gbl/find_library_use_libx32_paths#prop_gbl:FIND_LIBRARY_USE_LIBX32_PATHS "FIND_LIBRARY_USE_LIBX32_PATHS"), and [`FIND_LIBRARY_USE_LIB64_PATHS`](../prop_gbl/find_library_use_lib64_paths#prop_gbl:FIND_LIBRARY_USE_LIB64_PATHS "FIND_LIBRARY_USE_LIB64_PATHS") global properties.
If the [`FIND_LIBRARY_USE_LIB32_PATHS`](../prop_gbl/find_library_use_lib32_paths#prop_gbl:FIND_LIBRARY_USE_LIB32_PATHS "FIND_LIBRARY_USE_LIB32_PATHS") global property is set all search paths will be tested as normal, with `32/` appended, and with all matches of `lib/` replaced with `lib32/`. This property is automatically set for the platforms that are known to need it if at least one of the languages supported by the [`project()`](project#command:project "project") command is enabled.
If the [`FIND_LIBRARY_USE_LIBX32_PATHS`](../prop_gbl/find_library_use_libx32_paths#prop_gbl:FIND_LIBRARY_USE_LIBX32_PATHS "FIND_LIBRARY_USE_LIBX32_PATHS") global property is set all search paths will be tested as normal, with `x32/` appended, and with all matches of `lib/` replaced with `libx32/`. This property is automatically set for the platforms that are known to need it if at least one of the languages supported by the [`project()`](project#command:project "project") command is enabled.
If the [`FIND_LIBRARY_USE_LIB64_PATHS`](../prop_gbl/find_library_use_lib64_paths#prop_gbl:FIND_LIBRARY_USE_LIB64_PATHS "FIND_LIBRARY_USE_LIB64_PATHS") global property is set all search paths will be tested as normal, with `64/` appended, and with all matches of `lib/` replaced with `lib64/`. This property is automatically set for the platforms that are known to need it if at least one of the languages supported by the [`project()`](project#command:project "project") command is enabled.
| programming_docs |
cmake find_package find\_package
=============
Load settings for an external project.
```
find_package(<package> [version] [EXACT] [QUIET] [MODULE]
[REQUIRED] [[COMPONENTS] [components...]]
[OPTIONAL_COMPONENTS components...]
[NO_POLICY_SCOPE])
```
Finds and loads settings from an external project. `<package>_FOUND` will be set to indicate whether the package was found. When the package is found package-specific information is provided through variables and [Imported Targets](../manual/cmake-buildsystem.7#imported-targets) documented by the package itself. The `QUIET` option disables messages if the package cannot be found. The `MODULE` option disables the second signature documented below. The `REQUIRED` option stops processing with an error message if the package cannot be found.
A package-specific list of required components may be listed after the `COMPONENTS` option (or after the `REQUIRED` option if present). Additional optional components may be listed after `OPTIONAL_COMPONENTS`. Available components and their influence on whether a package is considered to be found are defined by the target package.
The `[version]` argument requests a version with which the package found should be compatible (format is `major[.minor[.patch[.tweak]]]`). The `EXACT` option requests that the version be matched exactly. If no `[version]` and/or component list is given to a recursive invocation inside a find-module, the corresponding arguments are forwarded automatically from the outer call (including the `EXACT` flag for `[version]`). Version support is currently provided only on a package-by-package basis (details below).
User code should generally look for packages using the above simple signature. The remainder of this command documentation specifies the full command signature and details of the search process. Project maintainers wishing to provide a package to be found by this command are encouraged to read on.
The command has two modes by which it searches for packages: “Module” mode and “Config” mode. Module mode is available when the command is invoked with the above reduced signature. CMake searches for a file called `Find<package>.cmake` in the [`CMAKE_MODULE_PATH`](../variable/cmake_module_path#variable:CMAKE_MODULE_PATH "CMAKE_MODULE_PATH") followed by the CMake installation. If the file is found, it is read and processed by CMake. It is responsible for finding the package, checking the version, and producing any needed messages. Many find-modules provide limited or no support for versioning; check the module documentation. If no module is found and the `MODULE` option is not given the command proceeds to Config mode.
The complete Config mode command signature is:
```
find_package(<package> [version] [EXACT] [QUIET]
[REQUIRED] [[COMPONENTS] [components...]]
[CONFIG|NO_MODULE]
[NO_POLICY_SCOPE]
[NAMES name1 [name2 ...]]
[CONFIGS config1 [config2 ...]]
[HINTS path1 [path2 ... ]]
[PATHS path1 [path2 ... ]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[NO_DEFAULT_PATH]
[NO_CMAKE_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[NO_SYSTEM_ENVIRONMENT_PATH]
[NO_CMAKE_PACKAGE_REGISTRY]
[NO_CMAKE_BUILDS_PATH] # Deprecated; does nothing.
[NO_CMAKE_SYSTEM_PATH]
[NO_CMAKE_SYSTEM_PACKAGE_REGISTRY]
[CMAKE_FIND_ROOT_PATH_BOTH |
ONLY_CMAKE_FIND_ROOT_PATH |
NO_CMAKE_FIND_ROOT_PATH])
```
The `CONFIG` option may be used to skip Module mode explicitly and switch to Config mode. It is synonymous to using `NO_MODULE`. Config mode is also implied by use of options not specified in the reduced signature.
Config mode attempts to locate a configuration file provided by the package to be found. A cache entry called `<package>_DIR` is created to hold the directory containing the file. By default the command searches for a package with the name `<package>`. If the `NAMES` option is given the names following it are used instead of `<package>`. The command searches for a file called `<name>Config.cmake` or `<lower-case-name>-config.cmake` for each name specified. A replacement set of possible configuration file names may be given using the `CONFIGS` option. The search procedure is specified below. Once found, the configuration file is read and processed by CMake. Since the file is provided by the package it already knows the location of package contents. The full path to the configuration file is stored in the cmake variable `<package>_CONFIG`.
All configuration files which have been considered by CMake while searching for an installation of the package with an appropriate version are stored in the cmake variable `<package>_CONSIDERED_CONFIGS`, the associated versions in `<package>_CONSIDERED_VERSIONS`.
If the package configuration file cannot be found CMake will generate an error describing the problem unless the `QUIET` argument is specified. If `REQUIRED` is specified and the package is not found a fatal error is generated and the configure step stops executing. If `<package>_DIR` has been set to a directory not containing a configuration file CMake will ignore it and search from scratch.
When the `[version]` argument is given Config mode will only find a version of the package that claims compatibility with the requested version (format is `major[.minor[.patch[.tweak]]]`). If the `EXACT` option is given only a version of the package claiming an exact match of the requested version may be found. CMake does not establish any convention for the meaning of version numbers. Package version numbers are checked by “version” files provided by the packages themselves. For a candidate package configuration file `<config-file>.cmake` the corresponding version file is located next to it and named either `<config-file>-version.cmake` or `<config-file>Version.cmake`. If no such version file is available then the configuration file is assumed to not be compatible with any requested version. A basic version file containing generic version matching code can be created using the [`CMakePackageConfigHelpers`](../module/cmakepackageconfighelpers#module:CMakePackageConfigHelpers "CMakePackageConfigHelpers") module. When a version file is found it is loaded to check the requested version number. The version file is loaded in a nested scope in which the following variables have been defined:
`PACKAGE_FIND_NAME` the `<package>` name
`PACKAGE_FIND_VERSION` full requested version string
`PACKAGE_FIND_VERSION_MAJOR` major version if requested, else 0
`PACKAGE_FIND_VERSION_MINOR` minor version if requested, else 0
`PACKAGE_FIND_VERSION_PATCH` patch version if requested, else 0
`PACKAGE_FIND_VERSION_TWEAK` tweak version if requested, else 0
`PACKAGE_FIND_VERSION_COUNT` number of version components, 0 to 4 The version file checks whether it satisfies the requested version and sets these variables:
`PACKAGE_VERSION` full provided version string
`PACKAGE_VERSION_EXACT` true if version is exact match
`PACKAGE_VERSION_COMPATIBLE` true if version is compatible
`PACKAGE_VERSION_UNSUITABLE` true if unsuitable as any version These variables are checked by the `find_package` command to determine whether the configuration file provides an acceptable version. They are not available after the find\_package call returns. If the version is acceptable the following variables are set:
`<package>_VERSION` full provided version string
`<package>_VERSION_MAJOR` major version if provided, else 0
`<package>_VERSION_MINOR` minor version if provided, else 0
`<package>_VERSION_PATCH` patch version if provided, else 0
`<package>_VERSION_TWEAK` tweak version if provided, else 0
`<package>_VERSION_COUNT` number of version components, 0 to 4 and the corresponding package configuration file is loaded. When multiple package configuration files are available whose version files claim compatibility with the version requested it is unspecified which one is chosen: unless the variable [`CMAKE_FIND_PACKAGE_SORT_ORDER`](../variable/cmake_find_package_sort_order#variable:CMAKE_FIND_PACKAGE_SORT_ORDER "CMAKE_FIND_PACKAGE_SORT_ORDER") is set no attempt is made to choose a highest or closest version number.
To control the order in which `find_package` checks for compatibiliy use the two variables [`CMAKE_FIND_PACKAGE_SORT_ORDER`](../variable/cmake_find_package_sort_order#variable:CMAKE_FIND_PACKAGE_SORT_ORDER "CMAKE_FIND_PACKAGE_SORT_ORDER") and [`CMAKE_FIND_PACKAGE_SORT_DIRECTION`](../variable/cmake_find_package_sort_direction#variable:CMAKE_FIND_PACKAGE_SORT_DIRECTION "CMAKE_FIND_PACKAGE_SORT_DIRECTION"). For instance in order to select the highest version one can set:
```
SET(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL)
SET(CMAKE_FIND_PACKAGE_SORT_DIRECTION DEC)
```
before calling `find_package`.
Config mode provides an elaborate interface and search procedure. Much of the interface is provided for completeness and for use internally by find-modules loaded by Module mode. Most user code should simply call:
```
find_package(<package> [major[.minor]] [EXACT] [REQUIRED|QUIET])
```
in order to find a package. Package maintainers providing CMake package configuration files are encouraged to name and install them such that the procedure outlined below will find them without requiring use of additional options.
CMake constructs a set of possible installation prefixes for the package. Under each prefix several directories are searched for a configuration file. The tables below show the directories searched. Each entry is meant for installation trees following Windows (W), UNIX (U), or Apple (A) conventions:
```
<prefix>/ (W)
<prefix>/(cmake|CMake)/ (W)
<prefix>/<name>*/ (W)
<prefix>/<name>*/(cmake|CMake)/ (W)
<prefix>/(lib/<arch>|lib|share)/cmake/<name>*/ (U)
<prefix>/(lib/<arch>|lib|share)/<name>*/ (U)
<prefix>/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/ (U)
<prefix>/<name>*/(lib/<arch>|lib|share)/cmake/<name>*/ (W/U)
<prefix>/<name>*/(lib/<arch>|lib|share)/<name>*/ (W/U)
<prefix>/<name>*/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/ (W/U)
```
On systems supporting OS X Frameworks and Application Bundles the following directories are searched for frameworks or bundles containing a configuration file:
```
<prefix>/<name>.framework/Resources/ (A)
<prefix>/<name>.framework/Resources/CMake/ (A)
<prefix>/<name>.framework/Versions/*/Resources/ (A)
<prefix>/<name>.framework/Versions/*/Resources/CMake/ (A)
<prefix>/<name>.app/Contents/Resources/ (A)
<prefix>/<name>.app/Contents/Resources/CMake/ (A)
```
In all cases the `<name>` is treated as case-insensitive and corresponds to any of the names specified (`<package>` or names given by `NAMES`). Paths with `lib/<arch>` are enabled if the [`CMAKE_LIBRARY_ARCHITECTURE`](../variable/cmake_library_architecture#variable:CMAKE_LIBRARY_ARCHITECTURE "CMAKE_LIBRARY_ARCHITECTURE") variable is set. If `PATH_SUFFIXES` is specified the suffixes are appended to each (W) or (U) directory entry one-by-one.
This set of directories is intended to work in cooperation with projects that provide configuration files in their installation trees. Directories above marked with (W) are intended for installations on Windows where the prefix may point at the top of an application’s installation directory. Those marked with (U) are intended for installations on UNIX platforms where the prefix is shared by multiple packages. This is merely a convention, so all (W) and (U) directories are still searched on all platforms. Directories marked with (A) are intended for installations on Apple platforms. The [`CMAKE_FIND_FRAMEWORK`](../variable/cmake_find_framework#variable:CMAKE_FIND_FRAMEWORK "CMAKE_FIND_FRAMEWORK") and [`CMAKE_FIND_APPBUNDLE`](../variable/cmake_find_appbundle#variable:CMAKE_FIND_APPBUNDLE "CMAKE_FIND_APPBUNDLE") variables determine the order of preference.
The set of installation prefixes is constructed using the following steps. If `NO_DEFAULT_PATH` is specified all `NO_*` options are enabled.
1. Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a `-DVAR=value`. The values are interpreted as [;-lists](../manual/cmake-language.7#cmake-language-lists). This can be skipped if `NO_CMAKE_PATH` is passed:
```
CMAKE_PREFIX_PATH
CMAKE_FRAMEWORK_PATH
CMAKE_APPBUNDLE_PATH
```
2. Search paths specified in cmake-specific environment variables. These are intended to be set in the user’s shell configuration, and therefore use the host’s native path separator (`;` on Windows and `:` on UNIX). This can be skipped if `NO_CMAKE_ENVIRONMENT_PATH` is passed:
```
<package>_DIR
CMAKE_PREFIX_PATH
CMAKE_FRAMEWORK_PATH
CMAKE_APPBUNDLE_PATH
```
3. Search paths specified by the `HINTS` option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the `PATHS` option.
4. Search the standard system environment variables. This can be skipped if `NO_SYSTEM_ENVIRONMENT_PATH` is passed. Path entries ending in `/bin` or `/sbin` are automatically converted to their parent directories:
```
PATH
```
5. Search paths stored in the CMake [User Package Registry](../manual/cmake-packages.7#user-package-registry). This can be skipped if `NO_CMAKE_PACKAGE_REGISTRY` is passed or by setting the [`CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY`](../variable/cmake_find_package_no_package_registry#variable:CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY "CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY") to `TRUE`. See the [`cmake-packages(7)`](../manual/cmake-packages.7#manual:cmake-packages(7) "cmake-packages(7)") manual for details on the user package registry.
6. Search cmake variables defined in the Platform files for the current system. This can be skipped if `NO_CMAKE_SYSTEM_PATH` is passed:
```
CMAKE_SYSTEM_PREFIX_PATH
CMAKE_SYSTEM_FRAMEWORK_PATH
CMAKE_SYSTEM_APPBUNDLE_PATH
```
7. Search paths stored in the CMake [System Package Registry](../manual/cmake-packages.7#system-package-registry). This can be skipped if `NO_CMAKE_SYSTEM_PACKAGE_REGISTRY` is passed or by setting the [`CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY`](../variable/cmake_find_package_no_system_package_registry#variable:CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY "CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY") to `TRUE`. See the [`cmake-packages(7)`](../manual/cmake-packages.7#manual:cmake-packages(7) "cmake-packages(7)") manual for details on the system package registry.
8. Search paths specified by the `PATHS` option. These are typically hard-coded guesses.
The CMake variable [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") specifies one or more directories to be prepended to all other search directories. This effectively “re-roots” the entire search under given locations. Paths which are descendants of the [`CMAKE_STAGING_PREFIX`](../variable/cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX") are excluded from this re-rooting, because that variable is always a path on the host system. By default the [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") is empty.
The [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") variable can also be used to specify exactly one directory to use as a prefix. Setting [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") also has other effects. See the documentation for that variable for more.
These variables are especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") are searched, then the [`CMAKE_SYSROOT`](../variable/cmake_sysroot#variable:CMAKE_SYSROOT "CMAKE_SYSROOT") directory is searched, and then the non-rooted directories will be searched. The default behavior can be adjusted by setting [`CMAKE_FIND_ROOT_PATH_MODE_PACKAGE`](../variable/cmake_find_root_path_mode_package#variable:CMAKE_FIND_ROOT_PATH_MODE_PACKAGE "CMAKE_FIND_ROOT_PATH_MODE_PACKAGE"). This behavior can be manually overridden on a per-call basis using options:
`CMAKE_FIND_ROOT_PATH_BOTH` Search in the order described above.
`NO_CMAKE_FIND_ROOT_PATH` Do not use the [`CMAKE_FIND_ROOT_PATH`](../variable/cmake_find_root_path#variable:CMAKE_FIND_ROOT_PATH "CMAKE_FIND_ROOT_PATH") variable.
`ONLY_CMAKE_FIND_ROOT_PATH` Search only the re-rooted directories and directories below [`CMAKE_STAGING_PREFIX`](../variable/cmake_staging_prefix#variable:CMAKE_STAGING_PREFIX "CMAKE_STAGING_PREFIX"). The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the `NO_*` options:
```
find_package (<package> PATHS paths... NO_DEFAULT_PATH)
find_package (<package>)
```
Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.
Every non-REQUIRED `find_package` call can be disabled by setting the [`CMAKE_DISABLE_FIND_PACKAGE_<PackageName>`](# "CMAKE_DISABLE_FIND_PACKAGE_<PackageName>") variable to `TRUE`.
When loading a find module or package configuration file `find_package` defines variables to provide information about the call arguments (and restores their original state before returning):
`CMAKE_FIND_PACKAGE_NAME` the `<package>` name which is searched for
`<package>_FIND_REQUIRED` true if `REQUIRED` option was given
`<package>_FIND_QUIETLY` true if `QUIET` option was given
`<package>_FIND_VERSION` full requested version string
`<package>_FIND_VERSION_MAJOR` major version if requested, else 0
`<package>_FIND_VERSION_MINOR` minor version if requested, else 0
`<package>_FIND_VERSION_PATCH` patch version if requested, else 0
`<package>_FIND_VERSION_TWEAK` tweak version if requested, else 0
`<package>_FIND_VERSION_COUNT` number of version components, 0 to 4
`<package>_FIND_VERSION_EXACT` true if `EXACT` option was given
`<package>_FIND_COMPONENTS` list of requested components
`<package>_FIND_REQUIRED_<c>` true if component `<c>` is required, false if component `<c>` is optional In Module mode the loaded find module is responsible to honor the request detailed by these variables; see the find module for details. In Config mode `find_package` handles `REQUIRED`, `QUIET`, and `[version]` options automatically but leaves it to the package configuration file to handle components in a way that makes sense for the package. The package configuration file may set `<package>_FOUND` to false to tell `find_package` that component requirements are not satisfied.
See the [`cmake_policy()`](cmake_policy#command:cmake_policy "cmake_policy") command documentation for discussion of the `NO_POLICY_SCOPE` option.
cmake ctest_sleep ctest\_sleep
============
sleeps for some amount of time
```
ctest_sleep(<seconds>)
```
Sleep for given number of seconds.
```
ctest_sleep(<time1> <duration> <time2>)
```
Sleep for t=(time1 + duration - time2) seconds if t > 0.
cmake get_cmake_property get\_cmake\_property
====================
Get a global property of the CMake instance.
```
get_cmake_property(VAR property)
```
Get a global property from the CMake instance. The value of the property is stored in the variable `VAR`. If the property is not found, `VAR` will be set to “NOTFOUND”. See the [`cmake-properties(7)`](../manual/cmake-properties.7#manual:cmake-properties(7) "cmake-properties(7)") manual for available properties.
See also the [`get_property()`](get_property#command:get_property "get_property") command `GLOBAL` option.
In addition to global properties, this command (for historical reasons) also supports the [`VARIABLES`](../prop_dir/variables#prop_dir:VARIABLES "VARIABLES") and [`MACROS`](../prop_dir/macros#prop_dir:MACROS "MACROS") directory properties. It also supports a special `COMPONENTS` global property that lists the components given to the [`install()`](install#command:install "install") command.
| programming_docs |
cmake endforeach endforeach
==========
Ends a list of commands in a foreach block.
```
endforeach(expression)
```
See the [`foreach()`](foreach#command:foreach "foreach") command.
cmake set_source_files_properties set\_source\_files\_properties
==============================
Source files can have properties that affect how they are built.
```
set_source_files_properties([file1 [file2 [...]]]
PROPERTIES prop1 value1
[prop2 value2 [...]])
```
Set properties associated with source files using a key/value paired list. See [Properties on Source Files](../manual/cmake-properties.7#source-file-properties) for the list of properties known to CMake. Source file properties are visible only to targets added in the same directory (CMakeLists.txt).
cmake execute_process execute\_process
================
Execute one or more child processes.
```
execute_process(COMMAND <cmd1> [args1...]]
[COMMAND <cmd2> [args2...] [...]]
[WORKING_DIRECTORY <directory>]
[TIMEOUT <seconds>]
[RESULT_VARIABLE <variable>]
[OUTPUT_VARIABLE <variable>]
[ERROR_VARIABLE <variable>]
[INPUT_FILE <file>]
[OUTPUT_FILE <file>]
[ERROR_FILE <file>]
[OUTPUT_QUIET]
[ERROR_QUIET]
[OUTPUT_STRIP_TRAILING_WHITESPACE]
[ERROR_STRIP_TRAILING_WHITESPACE]
[ENCODING <name>])
```
Runs the given sequence of one or more commands in parallel with the standard output of each process piped to the standard input of the next. A single standard error pipe is used for all processes.
Options:
`COMMAND`
A child process command line.
CMake executes the child process using operating system APIs directly. All arguments are passed VERBATIM to the child process. No intermediate shell is used, so shell operators such as `>` are treated as normal arguments. (Use the `INPUT_*`, `OUTPUT_*`, and `ERROR_*` options to redirect stdin, stdout, and stderr.)
If a sequential execution of multiple commands is required, use multiple [`execute_process()`](#command:execute_process "execute_process") calls with a single `COMMAND` argument.
`WORKING_DIRECTORY` The named directory will be set as the current working directory of the child processes.
`TIMEOUT` The child processes will be terminated if they do not finish in the specified number of seconds (fractions are allowed).
`RESULT_VARIABLE` The variable will be set to contain the result of running the processes. This will be an integer return code from the last child or a string describing an error condition.
`OUTPUT_VARIABLE, ERROR_VARIABLE` The variable named will be set with the contents of the standard output and standard error pipes, respectively. If the same variable is named for both pipes their output will be merged in the order produced.
`INPUT_FILE, OUTPUT_FILE, ERROR_FILE` The file named will be attached to the standard input of the first process, standard output of the last process, or standard error of all processes, respectively. If the same file is named for both output and error then it will be used for both.
`OUTPUT_QUIET, ERROR_QUIET` The standard output or standard error results will be quietly ignored.
`ENCODING <name>`
On Windows, the encoding that is used to decode output from the process. Ignored on other platforms. Valid encoding names are:
`NONE` Perform no decoding. This assumes that the process output is encoded in the same way as CMake’s internal encoding (UTF-8). This is the default.
`AUTO` Use the current active console’s codepage or if that isn’t available then use ANSI.
`ANSI` Use the ANSI codepage.
`OEM` Use the original equipment manufacturer (OEM) code page.
`UTF8` Use the UTF-8 codepage. If more than one `OUTPUT_*` or `ERROR_*` option is given for the same pipe the precedence is not specified. If no `OUTPUT_*` or `ERROR_*` options are given the output will be shared with the corresponding pipes of the CMake process itself.
The [`execute_process()`](#command:execute_process "execute_process") command is a newer more powerful version of [`exec_program()`](exec_program#command:exec_program "exec_program"), but the old command has been kept for compatibility. Both commands run while CMake is processing the project prior to build system generation. Use [`add_custom_target()`](add_custom_target#command:add_custom_target "add_custom_target") and [`add_custom_command()`](add_custom_command#command:add_custom_command "add_custom_command") to create custom commands that run at build time.
cmake output_required_files output\_required\_files
=======================
Disallowed. See CMake Policy [`CMP0032`](../policy/cmp0032#policy:CMP0032 "CMP0032").
Approximate C preprocessor dependency scanning.
This command exists only because ancient CMake versions provided it. CMake handles preprocessor dependency scanning automatically using a more advanced scanner.
```
output_required_files(srcfile outputfile)
```
Outputs a list of all the source files that are required by the specified srcfile. This list is written into outputfile. This is similar to writing out the dependencies for srcfile except that it jumps from .h files into .cxx, .c and .cpp files if possible.
cmake include_regular_expression include\_regular\_expression
============================
Set the regular expression used for dependency checking.
```
include_regular_expression(regex_match [regex_complain])
```
Set the regular expressions used in dependency checking. Only files matching `regex_match` will be traced as dependencies. Only files matching `regex_complain` will generate warnings if they cannot be found (standard header paths are not searched). The defaults are:
```
regex_match = "^.*$" (match everything)
regex_complain = "^$" (match empty string only)
```
cmake elseif elseif
======
Starts the elseif portion of an if block.
```
elseif(expression)
```
See the [`if()`](if#command:if "if") command.
cmake add_custom_target add\_custom\_target
===================
Add a target with no output so it will always be built.
```
add_custom_target(Name [ALL] [command1 [args1...]]
[COMMAND command2 [args2...] ...]
[DEPENDS depend depend depend ... ]
[BYPRODUCTS [files...]]
[WORKING_DIRECTORY dir]
[COMMENT comment]
[VERBATIM] [USES_TERMINAL]
[COMMAND_EXPAND_LISTS]
[SOURCES src1 [src2...]])
```
Adds a target with the given name that executes the given commands. The target has no output file and is *always considered out of date* even if the commands try to create a file with the name of the target. Use the [`add_custom_command()`](add_custom_command#command:add_custom_command "add_custom_command") command to generate a file with dependencies. By default nothing depends on the custom target. Use the [`add_dependencies()`](add_dependencies#command:add_dependencies "add_dependencies") command to add dependencies to or from other targets.
The options are:
`ALL` Indicate that this target should be added to the default build target so that it will be run every time (the command cannot be called `ALL`).
`BYPRODUCTS`
Specify the files the command is expected to produce but whose modification time may or may not be updated on subsequent builds. If a byproduct name is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory. Each byproduct file will be marked with the [`GENERATED`](../prop_sf/generated#prop_sf:GENERATED "GENERATED") source file property automatically.
Explicit specification of byproducts is supported by the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator to tell the `ninja` build tool how to regenerate byproducts when they are missing. It is also useful when other build rules (e.g. custom commands) depend on the byproducts. Ninja requires a build rule for any generated file on which another rule depends even if there are order-only dependencies to ensure the byproducts will be available before their dependents build.
The `BYPRODUCTS` option is ignored on non-Ninja generators except to mark byproducts `GENERATED`.
`COMMAND`
Specify the command-line(s) to execute at build time. If more than one `COMMAND` is specified they will be executed in order, but *not* necessarily composed into a stateful shell or batch script. (To run a full script, use the [`configure_file()`](configure_file#command:configure_file "configure_file") command or the [`file(GENERATE)`](file#command:file "file") command to create it, and then specify a `COMMAND` to launch it.)
If `COMMAND` specifies an executable target name (created by the [`add_executable()`](add_executable#command:add_executable "add_executable") command) it will automatically be replaced by the location of the executable created at build time. If set, the [`CROSSCOMPILING_EMULATOR`](../prop_tgt/crosscompiling_emulator#prop_tgt:CROSSCOMPILING_EMULATOR "CROSSCOMPILING_EMULATOR") executable target property will also be prepended to the command to allow the executable to run on the host. Additionally a target-level dependency will be added so that the executable target will be built before this custom target.
Arguments to `COMMAND` may use [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)"). References to target names in generator expressions imply target-level dependencies.
The command and arguments are optional and if not specified an empty target will be created.
`COMMENT` Display the given message before the commands are executed at build time.
`DEPENDS`
Reference files and outputs of custom commands created with [`add_custom_command()`](add_custom_command#command:add_custom_command "add_custom_command") command calls in the same directory (`CMakeLists.txt` file). They will be brought up to date when the target is built.
Use the [`add_dependencies()`](add_dependencies#command:add_dependencies "add_dependencies") command to add dependencies on other targets.
`COMMAND_EXPAND_LISTS` Lists in `COMMAND` arguments will be expanded, including those created with [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)"), allowing `COMMAND` arguments such as `${CC} "-I$<JOIN:$<TARGET_PROPERTY:foo,INCLUDE_DIRECTORIES>,;-I>" foo.cc` to be properly expanded.
`SOURCES` Specify additional source files to be included in the custom target. Specified source files will be added to IDE project files for convenience in editing even if they have no build rules.
`VERBATIM` All arguments to the commands will be escaped properly for the build tool so that the invoked command receives each argument unchanged. Note that one level of escapes is still used by the CMake language processor before `add_custom_target` even sees the arguments. Use of `VERBATIM` is recommended as it enables correct behavior. When `VERBATIM` is not given the behavior is platform specific because there is no protection of tool-specific special characters.
`USES_TERMINAL` The command will be given direct access to the terminal if possible. With the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator, this places the command in the `console` [`pool`](../prop_gbl/job_pools#prop_gbl:JOB_POOLS "JOB_POOLS").
`WORKING_DIRECTORY` Execute the command with the given current working directory. If it is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory.
cmake ctest_empty_binary_directory ctest\_empty\_binary\_directory
===============================
empties the binary directory
```
ctest_empty_binary_directory( directory )
```
Removes a binary directory. This command will perform some checks prior to deleting the directory in an attempt to avoid malicious or accidental directory deletion.
cmake get_filename_component get\_filename\_component
========================
Get a specific component of a full filename.
```
get_filename_component(<VAR> <FileName> <COMP> [CACHE])
```
Set `<VAR>` to a component of `<FileName>`, where `<COMP>` is one of:
```
DIRECTORY = Directory without file name
NAME = File name without directory
EXT = File name longest extension (.b.c from d/a.b.c)
NAME_WE = File name without directory or longest extension
PATH = Legacy alias for DIRECTORY (use for CMake <= 2.8.11)
```
Paths are returned with forward slashes and have no trailing slashes. The longest file extension is always considered. If the optional `CACHE` argument is specified, the result variable is added to the cache.
```
get_filename_component(<VAR> <FileName>
<COMP> [BASE_DIR <BASE_DIR>]
[CACHE])
```
Set `<VAR>` to the absolute path of `<FileName>`, where `<COMP>` is one of:
```
ABSOLUTE = Full path to file
REALPATH = Full path to existing file with symlinks resolved
```
If the provided `<FileName>` is a relative path, it is evaluated relative to the given base directory `<BASE_DIR>`. If no base directory is provided, the default base directory will be [`CMAKE_CURRENT_SOURCE_DIR`](../variable/cmake_current_source_dir#variable:CMAKE_CURRENT_SOURCE_DIR "CMAKE_CURRENT_SOURCE_DIR").
Paths are returned with forward slashes and have no trailing slahes. If the optional `CACHE` argument is specified, the result variable is added to the cache.
```
get_filename_component(<VAR> <FileName>
PROGRAM [PROGRAM_ARGS <ARG_VAR>]
[CACHE])
```
The program in `<FileName>` will be found in the system search path or left as a full path. If `PROGRAM_ARGS` is present with `PROGRAM`, then any command-line arguments present in the `<FileName>` string are split from the program name and stored in `<ARG_VAR>`. This is used to separate a program name from its arguments in a command line string.
cmake install_files install\_files
==============
Deprecated. Use the [`install(FILES)`](install#command:install "install") command instead.
This command has been superceded by the [`install()`](install#command:install "install") command. It is provided for compatibility with older CMake code. The `FILES` form is directly replaced by the `FILES` form of the [`install()`](install#command:install "install") command. The regexp form can be expressed more clearly using the `GLOB` form of the [`file()`](file#command:file "file") command.
```
install_files(<dir> extension file file ...)
```
Create rules to install the listed files with the given extension into the given directory. Only files existing in the current source tree or its corresponding location in the binary tree may be listed. If a file specified already has an extension, that extension will be removed first. This is useful for providing lists of source files such as foo.cxx when you want the corresponding foo.h to be installed. A typical extension is ‘.h’.
```
install_files(<dir> regexp)
```
Any files in the current source directory that match the regular expression will be installed.
```
install_files(<dir> FILES file file ...)
```
Any files listed after the `FILES` keyword will be installed explicitly from the names given. Full paths are allowed in this form.
The directory `<dir>` is relative to the installation prefix, which is stored in the variable [`CMAKE_INSTALL_PREFIX`](../variable/cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX").
cmake file file
====
File manipulation command.
```
file(WRITE <filename> <content>...)
file(APPEND <filename> <content>...)
```
Write `<content>` into a file called `<filename>`. If the file does not exist, it will be created. If the file already exists, `WRITE` mode will overwrite it and `APPEND` mode will append to the end. (If the file is a build input, use the [`configure_file()`](configure_file#command:configure_file "configure_file") command to update the file only when its content changes.)
```
file(READ <filename> <variable>
[OFFSET <offset>] [LIMIT <max-in>] [HEX])
```
Read content from a file called `<filename>` and store it in a `<variable>`. Optionally start from the given `<offset>` and read at most `<max-in>` bytes. The `HEX` option causes data to be converted to a hexadecimal representation (useful for binary data).
```
file(STRINGS <filename> <variable> [<options>...])
```
Parse a list of ASCII strings from `<filename>` and store it in `<variable>`. Binary data in the file are ignored. Carriage return (`\r`, CR) characters are ignored. The options are:
`LENGTH_MAXIMUM <max-len>` Consider only strings of at most a given length.
`LENGTH_MINIMUM <min-len>` Consider only strings of at least a given length.
`LIMIT_COUNT <max-num>` Limit the number of distinct strings to be extracted.
`LIMIT_INPUT <max-in>` Limit the number of input bytes to read from the file.
`LIMIT_OUTPUT <max-out>` Limit the number of total bytes to store in the `<variable>`.
`NEWLINE_CONSUME` Treat newline characters (`\n`, LF) as part of string content instead of terminating at them.
`NO_HEX_CONVERSION` Intel Hex and Motorola S-record files are automatically converted to binary while reading unless this option is given.
`REGEX <regex>` Consider only strings that match the given regular expression.
`ENCODING <encoding-type>` Consider strings of a given encoding. Currently supported encodings are: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. If the ENCODING option is not provided and the file has a Byte Order Mark, the ENCODING option will be defaulted to respect the Byte Order Mark. For example, the code
```
file(STRINGS myfile.txt myfile)
```
stores a list in the variable `myfile` in which each item is a line from the input file.
```
file(<HASH> <filename> <variable>)
```
Compute a cryptographic hash of the content of `<filename>` and store it in a `<variable>`. The supported `<HASH>` algorithm names are those listed by the [string(<HASH>)](string#supported-hash-algorithms) command.
```
file(GLOB <variable>
[LIST_DIRECTORIES true|false] [RELATIVE <path>]
[<globbing-expressions>...])
file(GLOB_RECURSE <variable> [FOLLOW_SYMLINKS]
[LIST_DIRECTORIES true|false] [RELATIVE <path>]
[<globbing-expressions>...])
```
Generate a list of files that match the `<globbing-expressions>` and store it into the `<variable>`. Globbing expressions are similar to regular expressions, but much simpler. If `RELATIVE` flag is specified, the results will be returned as relative paths to the given path. No specific order of results is defined other than that it is deterministic. If order is important then sort the list explicitly (e.g. using the [`list(SORT)`](list#command:list "list") command).
By default `GLOB` lists directories - directories are omited in result if `LIST_DIRECTORIES` is set to false.
Note
We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate.
Examples of globbing expressions include:
```
*.cxx - match all files with extension cxx
*.vt? - match all files with extension vta,...,vtz
f[3-5].txt - match files f3.txt, f4.txt, f5.txt
```
The `GLOB_RECURSE` mode will traverse all the subdirectories of the matched directory and match the files. Subdirectories that are symlinks are only traversed if `FOLLOW_SYMLINKS` is given or policy [`CMP0009`](../policy/cmp0009#policy:CMP0009 "CMP0009") is not set to `NEW`.
By default `GLOB_RECURSE` omits directories from result list - setting `LIST_DIRECTORIES` to true adds directories to result list. If `FOLLOW_SYMLINKS` is given or policy [`CMP0009`](../policy/cmp0009#policy:CMP0009 "CMP0009") is not set to `OLD` then `LIST_DIRECTORIES` treats symlinks as directories.
Examples of recursive globbing include:
```
/dir/*.py - match all python files in /dir and subdirectories
```
```
file(RENAME <oldname> <newname>)
```
Move a file or directory within a filesystem from `<oldname>` to `<newname>`, replacing the destination atomically.
```
file(REMOVE [<files>...])
file(REMOVE_RECURSE [<files>...])
```
Remove the given files. The `REMOVE_RECURSE` mode will remove the given files and directories, also non-empty directories. No error is emitted if a given file does not exist.
```
file(MAKE_DIRECTORY [<directories>...])
```
Create the given directories and their parents as needed.
```
file(RELATIVE_PATH <variable> <directory> <file>)
```
Compute the relative path from a `<directory>` to a `<file>` and store it in the `<variable>`.
```
file(TO_CMAKE_PATH "<path>" <variable>)
file(TO_NATIVE_PATH "<path>" <variable>)
```
The `TO_CMAKE_PATH` mode converts a native `<path>` into a cmake-style path with forward-slashes (`/`). The input can be a single path or a system search path like `$ENV{PATH}`. A search path will be converted to a cmake-style list separated by `;` characters.
The `TO_NATIVE_PATH` mode converts a cmake-style `<path>` into a native path with platform-specific slashes (`\` on Windows and `/` elsewhere).
Always use double quotes around the `<path>` to be sure it is treated as a single argument to this command.
```
file(DOWNLOAD <url> <file> [<options>...])
file(UPLOAD <file> <url> [<options>...])
```
The `DOWNLOAD` mode downloads the given `<url>` to a local `<file>`. The `UPLOAD` mode uploads a local `<file>` to a given `<url>`.
Options to both `DOWNLOAD` and `UPLOAD` are:
`INACTIVITY_TIMEOUT <seconds>` Terminate the operation after a period of inactivity.
`LOG <variable>` Store a human-readable log of the operation in a variable.
`SHOW_PROGRESS` Print progress information as status messages until the operation is complete.
`STATUS <variable>` Store the resulting status of the operation in a variable. The status is a `;` separated list of length 2. The first element is the numeric return value for the operation, and the second element is a string value for the error. A `0` numeric error means no error in the operation.
`TIMEOUT <seconds>` Terminate the operation after a given total time has elapsed.
`USERPWD <username>:<password>` Set username and password for operation.
`HTTPHEADER <HTTP-header>` HTTP header for operation. Suboption can be repeated several times. Additional options to `DOWNLOAD` are:
`EXPECTED_HASH ALGO=<value>`
Verify that the downloaded content hash matches the expected value, where `ALGO` is one of the algorithms supported by `file(<HASH>)`. If it does not match, the operation fails with an error.
`EXPECTED_MD5 <value>` Historical short-hand for `EXPECTED_HASH MD5=<value>`.
`TLS_VERIFY <ON|OFF>` Specify whether to verify the server certificate for `https://` URLs. The default is to *not* verify.
`TLS_CAINFO <file>` Specify a custom Certificate Authority file for `https://` URLs. For `https://` URLs CMake must be built with OpenSSL support. `TLS/SSL` certificates are not checked by default. Set `TLS_VERIFY` to `ON` to check certificates and/or use `EXPECTED_HASH` to verify downloaded content. If neither `TLS` option is given CMake will check variables `CMAKE_TLS_VERIFY` and `CMAKE_TLS_CAINFO`, respectively.
```
file(TIMESTAMP <filename> <variable> [<format>] [UTC])
```
Compute a string representation of the modification time of `<filename>` and store it in `<variable>`. Should the command be unable to obtain a timestamp variable will be set to the empty string (“”).
See the [`string(TIMESTAMP)`](string#command:string "string") command for documentation of the `<format>` and `UTC` options.
```
file(GENERATE OUTPUT output-file
<INPUT input-file|CONTENT content>
[CONDITION expression])
```
Generate an output file for each build configuration supported by the current [`CMake Generator`](../manual/cmake-generators.7#manual:cmake-generators(7) "cmake-generators(7)"). Evaluate [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") from the input content to produce the output content. The options are:
`CONDITION <condition>` Generate the output file for a particular configuration only if the condition is true. The condition must be either `0` or `1` after evaluating generator expressions.
`CONTENT <content>` Use the content given explicitly as input.
`INPUT <input-file>` Use the content from a given file as input.
`OUTPUT <output-file>` Specify the output file name to generate. Use generator expressions such as `$<CONFIG>` to specify a configuration-specific output file name. Multiple configurations may generate the same output file only if the generated content is identical. Otherwise, the `<output-file>` must evaluate to an unique name for each configuration. Exactly one `CONTENT` or `INPUT` option must be given. A specific `OUTPUT` file may be named by at most one invocation of `file(GENERATE)`. Generated files are modified on subsequent cmake runs only if their content is changed.
Note also that `file(GENERATE)` does not create the output file until the generation phase. The output file will not yet have been written when the `file(GENERATE)` command returns, it is written only after processing all of a project’s `CMakeLists.txt` files.
```
file(<COPY|INSTALL> <files>... DESTINATION <dir>
[FILE_PERMISSIONS <permissions>...]
[DIRECTORY_PERMISSIONS <permissions>...]
[NO_SOURCE_PERMISSIONS] [USE_SOURCE_PERMISSIONS]
[FILES_MATCHING]
[[PATTERN <pattern> | REGEX <regex>]
[EXCLUDE] [PERMISSIONS <permissions>...]] [...])
```
The `COPY` signature copies files, directories, and symlinks to a destination folder. Relative input paths are evaluated with respect to the current source directory, and a relative destination is evaluated with respect to the current build directory. Copying preserves input file timestamps, and optimizes out a file if it exists at the destination with the same timestamp. Copying preserves input permissions unless explicit permissions or `NO_SOURCE_PERMISSIONS` are given (default is `USE_SOURCE_PERMISSIONS`).
See the [`install(DIRECTORY)`](install#command:install "install") command for documentation of permissions, `FILES_MATCHING`, `PATTERN`, `REGEX`, and `EXCLUDE` options. Copying directories preserves the structure of their content even if options are used to select a subset of files.
The `INSTALL` signature differs slightly from `COPY`: it prints status messages (subject to the [`CMAKE_INSTALL_MESSAGE`](../variable/cmake_install_message#variable:CMAKE_INSTALL_MESSAGE "CMAKE_INSTALL_MESSAGE") variable), and `NO_SOURCE_PERMISSIONS` is default. Installation scripts generated by the [`install()`](install#command:install "install") command use this signature (with some undocumented options for internal use).
```
file(LOCK <path> [DIRECTORY] [RELEASE]
[GUARD <FUNCTION|FILE|PROCESS>]
[RESULT_VARIABLE <variable>]
[TIMEOUT <seconds>])
```
Lock a file specified by `<path>` if no `DIRECTORY` option present and file `<path>/cmake.lock` otherwise. File will be locked for scope defined by `GUARD` option (default value is `PROCESS`). `RELEASE` option can be used to unlock file explicitly. If option `TIMEOUT` is not specified CMake will wait until lock succeed or until fatal error occurs. If `TIMEOUT` is set to `0` lock will be tried once and result will be reported immediately. If `TIMEOUT` is not `0` CMake will try to lock file for the period specified by `<seconds>` value. Any errors will be interpreted as fatal if there is no `RESULT_VARIABLE` option. Otherwise result will be stored in `<variable>` and will be `0` on success or error message on failure.
Note that lock is advisory - there is no guarantee that other processes will respect this lock, i.e. lock synchronize two or more CMake instances sharing some modifiable resources. Similar logic applied to `DIRECTORY` option - locking parent directory doesn’t prevent other `LOCK` commands to lock any child directory or file.
Trying to lock file twice is not allowed. Any intermediate directories and file itself will be created if they not exist. `GUARD` and `TIMEOUT` options ignored on `RELEASE` operation.
| programming_docs |
cmake ctest_update ctest\_update
=============
Perform the [CTest Update Step](../manual/ctest.1#ctest-update-step) as a [Dashboard Client](../manual/ctest.1#dashboard-client).
```
ctest_update([SOURCE <source-dir>] [RETURN_VALUE <result-var>] [QUIET])
```
Update the source tree from version control and record results in `Update.xml` for submission with the [`ctest_submit()`](ctest_submit#command:ctest_submit "ctest_submit") command.
The options are:
`SOURCE <source-dir>` Specify the source directory. If not given, the [`CTEST_SOURCE_DIRECTORY`](../variable/ctest_source_directory#variable:CTEST_SOURCE_DIRECTORY "CTEST_SOURCE_DIRECTORY") variable is used.
`RETURN_VALUE <result-var>` Store in the `<result-var>` variable the number of files updated or `-1` on error.
`QUIET` Tell CTest to suppress most non-error messages that it would have otherwise printed to the console. CTest will still report the new revision of the repository and any conflicting files that were found. The update always follows the version control branch currently checked out in the source directory. See the [CTest Update Step](../manual/ctest.1#ctest-update-step) documentation for more information.
cmake variable_watch variable\_watch
===============
Watch the CMake variable for change.
```
variable_watch(<variable name> [<command to execute>])
```
If the specified variable changes, the message will be printed about the variable being changed. If the command is specified, the command will be executed. The command will receive the following arguments: COMMAND(<variable> <access> <value> <current list file> <stack>)
cmake include_directories include\_directories
====================
Add include directories to the build.
```
include_directories([AFTER|BEFORE] [SYSTEM] dir1 [dir2 ...])
```
Add the given directories to those the compiler uses to search for include files. Relative paths are interpreted as relative to the current source directory.
The include directories are added to the [`INCLUDE_DIRECTORIES`](../prop_dir/include_directories#prop_dir:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES") directory property for the current `CMakeLists` file. They are also added to the [`INCLUDE_DIRECTORIES`](../prop_tgt/include_directories#prop_tgt:INCLUDE_DIRECTORIES "INCLUDE_DIRECTORIES") target property for each target in the current `CMakeLists` file. The target property values are the ones used by the generators.
By default the directories specified are appended onto the current list of directories. This default behavior can be changed by setting [`CMAKE_INCLUDE_DIRECTORIES_BEFORE`](../variable/cmake_include_directories_before#variable:CMAKE_INCLUDE_DIRECTORIES_BEFORE "CMAKE_INCLUDE_DIRECTORIES_BEFORE") to `ON`. By using `AFTER` or `BEFORE` explicitly, you can select between appending and prepending, independent of the default.
If the `SYSTEM` option is given, the compiler will be told the directories are meant as system include directories on some platforms. Signalling this setting might achieve effects such as the compiler skipping warnings, or these fixed-install system files not being considered in dependency calculations - see compiler docs.
Arguments to `include_directories` may use “generator expressions” with the syntax “$<…>”. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake ctest_test ctest\_test
===========
Perform the [CTest Test Step](../manual/ctest.1#ctest-test-step) as a [Dashboard Client](../manual/ctest.1#dashboard-client).
```
ctest_test([BUILD <build-dir>] [APPEND]
[START <start-number>]
[END <end-number>]
[STRIDE <stride-number>]
[EXCLUDE <exclude-regex>]
[INCLUDE <include-regex>]
[EXCLUDE_LABEL <label-exclude-regex>]
[INCLUDE_LABEL <label-include-regex>]
[EXCLUDE_FIXTURE <regex>]
[EXCLUDE_FIXTURE_SETUP <regex>]
[EXCLUDE_FIXTURE_CLEANUP <regex>]
[PARALLEL_LEVEL <level>]
[TEST_LOAD <threshold>]
[SCHEDULE_RANDOM <ON|OFF>]
[STOP_TIME <time-of-day>]
[RETURN_VALUE <result-var>]
[CAPTURE_CMAKE_ERROR <result-var>]
[QUIET]
)
```
Run tests in the project build tree and store results in `Test.xml` for submission with the [`ctest_submit()`](ctest_submit#command:ctest_submit "ctest_submit") command.
The options are:
`BUILD <build-dir>` Specify the top-level build directory. If not given, the [`CTEST_BINARY_DIRECTORY`](../variable/ctest_binary_directory#variable:CTEST_BINARY_DIRECTORY "CTEST_BINARY_DIRECTORY") variable is used.
`APPEND` Mark `Test.xml` for append to results previously submitted to a dashboard server since the last [`ctest_start()`](ctest_start#command:ctest_start "ctest_start") call. Append semantics are defined by the dashboard server in use. This does *not* cause results to be appended to a `.xml` file produced by a previous call to this command.
`START <start-number>` Specify the beginning of a range of test numbers.
`END <end-number>` Specify the end of a range of test numbers.
`STRIDE <stride-number>` Specify the stride by which to step across a range of test numbers.
`EXCLUDE <exclude-regex>` Specify a regular expression matching test names to exclude.
`INCLUDE <include-regex>` Specify a regular expression matching test names to include. Tests not matching this expression are excluded.
`EXCLUDE_LABEL <label-exclude-regex>` Specify a regular expression matching test labels to exclude.
`INCLUDE_LABEL <label-include-regex>` Specify a regular expression matching test labels to include. Tests not matching this expression are excluded.
`EXCLUDE_FIXTURE <regex>` If a test in the set of tests to be executed requires a particular fixture, that fixture’s setup and cleanup tests would normally be added to the test set automatically. This option prevents adding setup or cleanup tests for fixtures matching the `<regex>`. Note that all other fixture behavior is retained, including test dependencies and skipping tests that have fixture setup tests that fail.
`EXCLUDE_FIXTURE_SETUP <regex>` Same as `EXCLUDE_FIXTURE` except only matching setup tests are excluded.
`EXCLUDE_FIXTURE_CLEANUP <regex>` Same as `EXCLUDE_FIXTURE` except only matching cleanup tests are excluded.
`PARALLEL_LEVEL <level>` Specify a positive number representing the number of tests to be run in parallel.
`TEST_LOAD <threshold>` While running tests in parallel, try not to start tests when they may cause the CPU load to pass above a given threshold. If not specified the [`CTEST_TEST_LOAD`](../variable/ctest_test_load#variable:CTEST_TEST_LOAD "CTEST_TEST_LOAD") variable will be checked, and then the `--test-load` command-line argument to [`ctest(1)`](../manual/ctest.1#manual:ctest(1) "ctest(1)"). See also the `TestLoad` setting in the [CTest Test Step](../manual/ctest.1#ctest-test-step).
`SCHEDULE_RANDOM <ON|OFF>` Launch tests in a random order. This may be useful for detecting implicit test dependencies.
`STOP_TIME <time-of-day>` Specify a time of day at which the tests should all stop running.
`RETURN_VALUE <result-var>` Store in the `<result-var>` variable `0` if all tests passed. Store non-zero if anything went wrong.
`CAPTURE_CMAKE_ERROR <result-var>` Store in the `<result-var>` variable -1 if there are any errors running the command and prevent ctest from returning non-zero if an error occurs.
`QUIET` Suppress any CTest-specific non-error messages that would have otherwise been printed to the console. Output from the underlying test command is not affected. Summary info detailing the percentage of passing tests is also unaffected by the `QUIET` option. See also the [`CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE`](../variable/ctest_custom_maximum_passed_test_output_size#variable:CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE "CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE") and [`CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE`](../variable/ctest_custom_maximum_failed_test_output_size#variable:CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE "CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE") variables.
cmake utility_source utility\_source
===============
Disallowed. See CMake Policy [`CMP0034`](../policy/cmp0034#policy:CMP0034 "CMP0034").
Specify the source tree of a third-party utility.
```
utility_source(cache_entry executable_name
path_to_source [file1 file2 ...])
```
When a third-party utility’s source is included in the distribution, this command specifies its location and name. The cache entry will not be set unless the `path_to_source` and all listed files exist. It is assumed that the source tree of the utility will have been built before it is needed.
When cross compiling CMake will print a warning if a `utility_source()` command is executed, because in many cases it is used to build an executable which is executed later on. This doesn’t work when cross compiling, since the executable can run only on their target platform. So in this case the cache entry has to be adjusted manually so it points to an executable which is runnable on the build host.
cmake target_link_libraries target\_link\_libraries
=======================
* [Overview](#overview)
* [Libraries for a Target and/or its Dependents](#libraries-for-a-target-and-or-its-dependents)
* [Libraries for both a Target and its Dependents](#libraries-for-both-a-target-and-its-dependents)
* [Libraries for a Target and/or its Dependents (Legacy)](#libraries-for-a-target-and-or-its-dependents-legacy)
* [Libraries for Dependents Only (Legacy)](#libraries-for-dependents-only-legacy)
* [Cyclic Dependencies of Static Libraries](#cyclic-dependencies-of-static-libraries)
* [Creating Relocatable Packages](#creating-relocatable-packages)
Specify libraries or flags to use when linking a given target and/or its dependents. [Usage requirements](../manual/cmake-buildsystem.7#target-usage-requirements) from linked library targets will be propagated. Usage requirements of a target’s dependencies affect compilation of its own sources.
Overview
--------
This command has several signatures as detailed in subsections below. All of them have the general form:
```
target_link_libraries(<target> ... <item>... ...)
```
The named `<target>` must have been created in the current directory by a command such as [`add_executable()`](add_executable#command:add_executable "add_executable") or [`add_library()`](add_library#command:add_library "add_library"). Repeated calls for the same `<target>` append items in the order called. Each `<item>` may be:
* **A library target name**: The generated link line will have the full path to the linkable library file associated with the target. The buildsystem will have a dependency to re-link `<target>` if the library file changes.
The named target must be created by [`add_library()`](add_library#command:add_library "add_library") within the project or as an [IMPORTED library](../manual/cmake-buildsystem.7#imported-targets). If it is created within the project an ordering dependency will automatically be added in the build system to make sure the named library target is up-to-date before the `<target>` links.
If an imported library has the [`IMPORTED_NO_SONAME`](../prop_tgt/imported_no_soname#prop_tgt:IMPORTED_NO_SONAME "IMPORTED_NO_SONAME") target property set, CMake may ask the linker to search for the library instead of using the full path (e.g. `/usr/lib/libfoo.so` becomes `-lfoo`).
* **A full path to a library file**: The generated link line will normally preserve the full path to the file. The buildsystem will have a dependency to re-link `<target>` if the library file changes.
There are some cases where CMake may ask the linker to search for the library (e.g. `/usr/lib/libfoo.so` becomes `-lfoo`), such as when a shared library is detected to have no `SONAME` field. See policy [`CMP0060`](../policy/cmp0060#policy:CMP0060 "CMP0060") for discussion of another case.
If the library file is in a Mac OSX framework, the `Headers` directory of the framework will also be processed as a [usage requirement](../manual/cmake-buildsystem.7#target-usage-requirements). This has the same effect as passing the framework directory as an include directory.
On [Visual Studio Generators](../manual/cmake-generators.7#visual-studio-generators) for VS 2010 and above, library files ending in `.targets` will be treated as MSBuild targets files and imported into generated project files. This is not supported by other generators.
* **A plain library name**: The generated link line will ask the linker to search for the library (e.g. `foo` becomes `-lfoo` or `foo.lib`).
* **A link flag**: Item names starting with `-`, but not `-l` or `-framework`, are treated as linker flags. Note that such flags will be treated like any other library link item for purposes of transitive dependencies, so they are generally safe to specify only as private link items that will not propagate to dependents.
Link flags specified here are inserted into the link command in the same place as the link libraries. This might not be correct, depending on the linker. Use the [`LINK_FLAGS`](../prop_tgt/link_flags#prop_tgt:LINK_FLAGS "LINK_FLAGS") target property to add link flags explicitly. The flags will then be placed at the toolchain-defined flag position in the link command.
* A `debug`, `optimized`, or `general` keyword immediately followed by another `<item>`. The item following such a keyword will be used only for the corresponding build configuration. The `debug` keyword corresponds to the `Debug` configuration (or to configurations named in the [`DEBUG_CONFIGURATIONS`](../prop_gbl/debug_configurations#prop_gbl:DEBUG_CONFIGURATIONS "DEBUG_CONFIGURATIONS") global property if it is set). The `optimized` keyword corresponds to all other configurations. The `general` keyword corresponds to all configurations, and is purely optional. Higher granularity may be achieved for per-configuration rules by creating and linking to [IMPORTED library targets](../manual/cmake-buildsystem.7#imported-targets).
Items containing `::`, such as `Foo::Bar`, are assumed to be [IMPORTED](../manual/cmake-buildsystem.7#imported-targets) or [ALIAS](../manual/cmake-buildsystem.7#alias-targets) library target names and will cause an error if no such target exists. See policy [`CMP0028`](../policy/cmp0028#policy:CMP0028 "CMP0028").
Arguments to `target_link_libraries` may use “generator expressions” with the syntax `$<...>`. Note however, that generator expressions will not be used in OLD handling of [`CMP0003`](../policy/cmp0003#policy:CMP0003 "CMP0003") or [`CMP0004`](../policy/cmp0004#policy:CMP0004 "CMP0004"). See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
Libraries for a Target and/or its Dependents
--------------------------------------------
```
target_link_libraries(<target>
<PRIVATE|PUBLIC|INTERFACE> <item>...
[<PRIVATE|PUBLIC|INTERFACE> <item>...]...)
```
The `PUBLIC`, `PRIVATE` and `INTERFACE` keywords can be used to specify both the link dependencies and the link interface in one command. Libraries and targets following `PUBLIC` are linked to, and are made part of the link interface. Libraries and targets following `PRIVATE` are linked to, but are not made part of the link interface. Libraries following `INTERFACE` are appended to the link interface and are not used for linking `<target>`.
Libraries for both a Target and its Dependents
----------------------------------------------
```
target_link_libraries(<target> <item>...)
```
Library dependencies are transitive by default with this signature. When this target is linked into another target then the libraries linked to this target will appear on the link line for the other target too. This transitive “link interface” is stored in the [`INTERFACE_LINK_LIBRARIES`](../prop_tgt/interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES") target property and may be overridden by setting the property directly. When [`CMP0022`](../policy/cmp0022#policy:CMP0022 "CMP0022") is not set to `NEW`, transitive linking is built in but may be overridden by the [`LINK_INTERFACE_LIBRARIES`](../prop_tgt/link_interface_libraries#prop_tgt:LINK_INTERFACE_LIBRARIES "LINK_INTERFACE_LIBRARIES") property. Calls to other signatures of this command may set the property making any libraries linked exclusively by this signature private.
Libraries for a Target and/or its Dependents (Legacy)
-----------------------------------------------------
```
target_link_libraries(<target>
<LINK_PRIVATE|LINK_PUBLIC> <lib>...
[<LINK_PRIVATE|LINK_PUBLIC> <lib>...]...)
```
The `LINK_PUBLIC` and `LINK_PRIVATE` modes can be used to specify both the link dependencies and the link interface in one command.
This signature is for compatibility only. Prefer the `PUBLIC` or `PRIVATE` keywords instead.
Libraries and targets following `LINK_PUBLIC` are linked to, and are made part of the [`INTERFACE_LINK_LIBRARIES`](../prop_tgt/interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES"). If policy [`CMP0022`](../policy/cmp0022#policy:CMP0022 "CMP0022") is not `NEW`, they are also made part of the [`LINK_INTERFACE_LIBRARIES`](../prop_tgt/link_interface_libraries#prop_tgt:LINK_INTERFACE_LIBRARIES "LINK_INTERFACE_LIBRARIES"). Libraries and targets following `LINK_PRIVATE` are linked to, but are not made part of the [`INTERFACE_LINK_LIBRARIES`](../prop_tgt/interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES") (or [`LINK_INTERFACE_LIBRARIES`](../prop_tgt/link_interface_libraries#prop_tgt:LINK_INTERFACE_LIBRARIES "LINK_INTERFACE_LIBRARIES")).
Libraries for Dependents Only (Legacy)
--------------------------------------
```
target_link_libraries(<target> LINK_INTERFACE_LIBRARIES <item>...)
```
The `LINK_INTERFACE_LIBRARIES` mode appends the libraries to the [`INTERFACE_LINK_LIBRARIES`](../prop_tgt/interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES") target property instead of using them for linking. If policy [`CMP0022`](../policy/cmp0022#policy:CMP0022 "CMP0022") is not `NEW`, then this mode also appends libraries to the [`LINK_INTERFACE_LIBRARIES`](../prop_tgt/link_interface_libraries#prop_tgt:LINK_INTERFACE_LIBRARIES "LINK_INTERFACE_LIBRARIES") and its per-configuration equivalent.
This signature is for compatibility only. Prefer the `INTERFACE` mode instead.
Libraries specified as `debug` are wrapped in a generator expression to correspond to debug builds. If policy [`CMP0022`](../policy/cmp0022#policy:CMP0022 "CMP0022") is not `NEW`, the libraries are also appended to the [`LINK_INTERFACE_LIBRARIES_DEBUG`](# "LINK_INTERFACE_LIBRARIES_<CONFIG>") property (or to the properties corresponding to configurations listed in the [`DEBUG_CONFIGURATIONS`](../prop_gbl/debug_configurations#prop_gbl:DEBUG_CONFIGURATIONS "DEBUG_CONFIGURATIONS") global property if it is set). Libraries specified as `optimized` are appended to the [`INTERFACE_LINK_LIBRARIES`](../prop_tgt/interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES") property. If policy [`CMP0022`](../policy/cmp0022#policy:CMP0022 "CMP0022") is not `NEW`, they are also appended to the [`LINK_INTERFACE_LIBRARIES`](../prop_tgt/link_interface_libraries#prop_tgt:LINK_INTERFACE_LIBRARIES "LINK_INTERFACE_LIBRARIES") property. Libraries specified as `general` (or without any keyword) are treated as if specified for both `debug` and `optimized`.
Cyclic Dependencies of Static Libraries
---------------------------------------
The library dependency graph is normally acyclic (a DAG), but in the case of mutually-dependent `STATIC` libraries CMake allows the graph to contain cycles (strongly connected components). When another target links to one of the libraries, CMake repeats the entire connected component. For example, the code
```
add_library(A STATIC a.c)
add_library(B STATIC b.c)
target_link_libraries(A B)
target_link_libraries(B A)
add_executable(main main.c)
target_link_libraries(main A)
```
links `main` to `A B A B`. While one repetition is usually sufficient, pathological object file and symbol arrangements can require more. One may handle such cases by using the [`LINK_INTERFACE_MULTIPLICITY`](../prop_tgt/link_interface_multiplicity#prop_tgt:LINK_INTERFACE_MULTIPLICITY "LINK_INTERFACE_MULTIPLICITY") target property or by manually repeating the component in the last `target_link_libraries` call. However, if two archives are really so interdependent they should probably be combined into a single archive, perhaps by using [Object Libraries](../manual/cmake-buildsystem.7#object-libraries).
Creating Relocatable Packages
-----------------------------
Note that it is not advisable to populate the [`INTERFACE_LINK_LIBRARIES`](../prop_tgt/interface_link_libraries#prop_tgt:INTERFACE_LINK_LIBRARIES "INTERFACE_LINK_LIBRARIES") of a target with absolute paths to dependencies. That would hard-code into installed packages the library file paths for dependencies **as found on the machine the package was made on**.
See the [Creating Relocatable Packages](../manual/cmake-packages.7#creating-relocatable-packages) section of the [`cmake-packages(7)`](../manual/cmake-packages.7#manual:cmake-packages(7) "cmake-packages(7)") manual for discussion of additional care that must be taken when specifying usage requirements while creating packages for redistribution.
| programming_docs |
cmake write_file write\_file
===========
Deprecated. Use the [`file(WRITE)`](file#command:file "file") command instead.
```
write_file(filename "message to write"... [APPEND])
```
The first argument is the file name, the rest of the arguments are messages to write. If the argument `APPEND` is specified, then the message will be appended.
NOTE 1: [`file(WRITE)`](file#command:file "file") and [`file(APPEND)`](file#command:file "file") do exactly the same as this one but add some more functionality.
NOTE 2: When using `write_file` the produced file cannot be used as an input to CMake (CONFIGURE\_FILE, source file …) because it will lead to an infinite loop. Use [`configure_file()`](configure_file#command:configure_file "configure_file") if you want to generate input files to CMake.
cmake macro macro
=====
Start recording a macro for later invocation as a command:
```
macro(<name> [arg1 [arg2 [arg3 ...]]])
COMMAND1(ARGS ...)
COMMAND2(ARGS ...)
...
endmacro(<name>)
```
Define a macro named `<name>` that takes arguments named `arg1`, `arg2`, `arg3`, (…). Commands listed after macro, but before the matching [`endmacro()`](endmacro#command:endmacro "endmacro"), are not invoked until the macro is invoked. When it is invoked, the commands recorded in the macro are first modified by replacing formal parameters (`${arg1}`) with the arguments passed, and then invoked as normal commands. In addition to referencing the formal parameters you can reference the values `${ARGC}` which will be set to the number of arguments passed into the function as well as `${ARGV0}`, `${ARGV1}`, `${ARGV2}`, … which will have the actual values of the arguments passed in. This facilitates creating macros with optional arguments. Additionally `${ARGV}` holds the list of all arguments given to the macro and `${ARGN}` holds the list of arguments past the last expected argument. Referencing to `${ARGV#}` arguments beyond `${ARGC}` have undefined behavior. Checking that `${ARGC}` is greater than `#` is the only way to ensure that `${ARGV#}` was passed to the function as an extra argument.
See the [`cmake_policy()`](cmake_policy#command:cmake_policy "cmake_policy") command documentation for the behavior of policies inside macros.
Macro Argument Caveats
----------------------
Note that the parameters to a macro and values such as `ARGN` are not variables in the usual CMake sense. They are string replacements much like the C preprocessor would do with a macro. Therefore you will NOT be able to use commands like:
```
if(ARGV1) # ARGV1 is not a variable
if(DEFINED ARGV2) # ARGV2 is not a variable
if(ARGC GREATER 2) # ARGC is not a variable
foreach(loop_var IN LISTS ARGN) # ARGN is not a variable
```
In the first case, you can use `if(${ARGV1})`. In the second and third case, the proper way to check if an optional variable was passed to the macro is to use `if(${ARGC} GREATER 2)`. In the last case, you can use `foreach(loop_var ${ARGN})` but this will skip empty arguments. If you need to include them, you can use:
```
set(list_var "${ARGN}")
foreach(loop_var IN LISTS list_var)
```
Note that if you have a variable with the same name in the scope from which the macro is called, using unreferenced names will use the existing variable instead of the arguments. For example:
```
macro(_BAR)
foreach(arg IN LISTS ARGN)
[...]
endforeach()
endmacro()
function(_FOO)
_bar(x y z)
endfunction()
_foo(a b c)
```
Will loop over `a;b;c` and not over `x;y;z` as one might be expecting. If you want true CMake variables and/or better CMake scope control you should look at the function command.
cmake target_sources target\_sources
===============
Add sources to a target.
```
target_sources(<target>
<INTERFACE|PUBLIC|PRIVATE> [items1...]
[<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
```
Specify sources to use when compiling a given target. The named `<target>` must have been created by a command such as [`add_executable()`](add_executable#command:add_executable "add_executable") or [`add_library()`](add_library#command:add_library "add_library") and must not be an [IMPORTED Target](../manual/cmake-buildsystem.7#imported-targets).
The `INTERFACE`, `PUBLIC` and `PRIVATE` keywords are required to specify the scope of the following arguments. `PRIVATE` and `PUBLIC` items will populate the [`SOURCES`](../prop_tgt/sources#prop_tgt:SOURCES "SOURCES") property of `<target>`. `PUBLIC` and `INTERFACE` items will populate the [`INTERFACE_SOURCES`](../prop_tgt/interface_sources#prop_tgt:INTERFACE_SOURCES "INTERFACE_SOURCES") property of `<target>`. The following arguments specify sources. Repeated calls for the same `<target>` append items in the order called.
Arguments to `target_sources` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake include_external_msproject include\_external\_msproject
============================
Include an external Microsoft project file in a workspace.
```
include_external_msproject(projectname location
[TYPE projectTypeGUID]
[GUID projectGUID]
[PLATFORM platformName]
dep1 dep2 ...)
```
Includes an external Microsoft project in the generated workspace file. Currently does nothing on UNIX. This will create a target named [projectname]. This can be used in the [`add_dependencies()`](add_dependencies#command:add_dependencies "add_dependencies") command to make things depend on the external project.
`TYPE`, `GUID` and `PLATFORM` are optional parameters that allow one to specify the type of project, id (GUID) of the project and the name of the target platform. This is useful for projects requiring values other than the default (e.g. WIX projects).
If the imported project has different configuration names than the current project, set the [`MAP_IMPORTED_CONFIG_<CONFIG>`](# "MAP_IMPORTED_CONFIG_<CONFIG>") target property to specify the mapping.
cmake try_compile try\_compile
============
* [Try Compiling Whole Projects](#try-compiling-whole-projects)
* [Try Compiling Source Files](#try-compiling-source-files)
* [Other Behavior Settings](#other-behavior-settings)
Try building some code.
Try Compiling Whole Projects
----------------------------
```
try_compile(RESULT_VAR <bindir> <srcdir>
<projectName> [<targetName>] [CMAKE_FLAGS <flags>...]
[OUTPUT_VARIABLE <var>])
```
Try building a project. The success or failure of the `try_compile`, i.e. `TRUE` or `FALSE` respectively, is returned in `RESULT_VAR`.
In this form, `<srcdir>` should contain a complete CMake project with a `CMakeLists.txt` file and all sources. The `<bindir>` and `<srcdir>` will not be deleted after this command is run. Specify `<targetName>` to build a specific target instead of the `all` or `ALL_BUILD` target. See below for the meaning of other options.
Try Compiling Source Files
--------------------------
```
try_compile(RESULT_VAR <bindir> <srcfile|SOURCES srcfile...>
[CMAKE_FLAGS <flags>...]
[COMPILE_DEFINITIONS <defs>...]
[LINK_LIBRARIES <libs>...]
[OUTPUT_VARIABLE <var>]
[COPY_FILE <fileName> [COPY_FILE_ERROR <var>]]
[<LANG>_STANDARD <std>]
[<LANG>_STANDARD_REQUIRED <bool>]
[<LANG>_EXTENSIONS <bool>]
)
```
Try building an executable from one or more source files. The success or failure of the `try_compile`, i.e. `TRUE` or `FALSE` respectively, is returned in `RESULT_VAR`.
In this form the user need only supply one or more source files that include a definition for `main`. CMake will create a `CMakeLists.txt` file to build the source(s) as an executable that looks something like this:
```
add_definitions(<expanded COMPILE_DEFINITIONS from caller>)
include_directories(${INCLUDE_DIRECTORIES})
link_directories(${LINK_DIRECTORIES})
add_executable(cmTryCompileExec <srcfile>...)
target_link_libraries(cmTryCompileExec ${LINK_LIBRARIES})
```
The options are:
`CMAKE_FLAGS <flags>...` Specify flags of the form `-DVAR:TYPE=VALUE` to be passed to the `cmake` command-line used to drive the test build. The above example shows how values for variables `INCLUDE_DIRECTORIES`, `LINK_DIRECTORIES`, and `LINK_LIBRARIES` are used.
`COMPILE_DEFINITIONS <defs>...` Specify `-Ddefinition` arguments to pass to `add_definitions` in the generated test project.
`COPY_FILE <fileName>` Copy the linked executable to the given `<fileName>`.
`COPY_FILE_ERROR <var>` Use after `COPY_FILE` to capture into variable `<var>` any error message encountered while trying to copy the file.
`LINK_LIBRARIES <libs>...`
Specify libraries to be linked in the generated project. The list of libraries may refer to system libraries and to [Imported Targets](../manual/cmake-buildsystem.7#imported-targets) from the calling project.
If this option is specified, any `-DLINK_LIBRARIES=...` value given to the `CMAKE_FLAGS` option will be ignored.
`OUTPUT_VARIABLE <var>` Store the output from the build process the given variable.
`<LANG>_STANDARD <std>` Specify the [`C_STANDARD`](../prop_tgt/c_standard#prop_tgt:C_STANDARD "C_STANDARD"), [`CXX_STANDARD`](../prop_tgt/cxx_standard#prop_tgt:CXX_STANDARD "CXX_STANDARD"), or [`CUDA_STANDARD`](../prop_tgt/cuda_standard#prop_tgt:CUDA_STANDARD "CUDA_STANDARD") target property of the generated project.
`<LANG>_STANDARD_REQUIRED <bool>` Specify the [`C_STANDARD_REQUIRED`](../prop_tgt/c_standard_required#prop_tgt:C_STANDARD_REQUIRED "C_STANDARD_REQUIRED"), [`CXX_STANDARD_REQUIRED`](../prop_tgt/cxx_standard_required#prop_tgt:CXX_STANDARD_REQUIRED "CXX_STANDARD_REQUIRED"), or [`CUDA_STANDARD_REQUIRED`](../prop_tgt/cuda_standard_required#prop_tgt:CUDA_STANDARD_REQUIRED "CUDA_STANDARD_REQUIRED") target property of the generated project.
`<LANG>_EXTENSIONS <bool>` Specify the [`C_EXTENSIONS`](../prop_tgt/c_extensions#prop_tgt:C_EXTENSIONS "C_EXTENSIONS"), [`CXX_EXTENSIONS`](../prop_tgt/cxx_extensions#prop_tgt:CXX_EXTENSIONS "CXX_EXTENSIONS"), or [`CUDA_EXTENSIONS`](../prop_tgt/cuda_extensions#prop_tgt:CUDA_EXTENSIONS "CUDA_EXTENSIONS") target property of the generated project. In this version all files in `<bindir>/CMakeFiles/CMakeTmp` will be cleaned automatically. For debugging, `--debug-trycompile` can be passed to `cmake` to avoid this clean. However, multiple sequential `try_compile` operations reuse this single output directory. If you use `--debug-trycompile`, you can only debug one `try_compile` call at a time. The recommended procedure is to protect all `try_compile` calls in your project by `if(NOT DEFINED RESULT_VAR)` logic, configure with cmake all the way through once, then delete the cache entry associated with the try\_compile call of interest, and then re-run cmake again with `--debug-trycompile`.
Other Behavior Settings
-----------------------
If set, the following variables are passed in to the generated try\_compile CMakeLists.txt to initialize compile target properties with default values:
* [`CMAKE_ENABLE_EXPORTS`](../variable/cmake_enable_exports#variable:CMAKE_ENABLE_EXPORTS "CMAKE_ENABLE_EXPORTS")
* [`CMAKE_LINK_SEARCH_START_STATIC`](../variable/cmake_link_search_start_static#variable:CMAKE_LINK_SEARCH_START_STATIC "CMAKE_LINK_SEARCH_START_STATIC")
* [`CMAKE_LINK_SEARCH_END_STATIC`](../variable/cmake_link_search_end_static#variable:CMAKE_LINK_SEARCH_END_STATIC "CMAKE_LINK_SEARCH_END_STATIC")
* [`CMAKE_POSITION_INDEPENDENT_CODE`](../variable/cmake_position_independent_code#variable:CMAKE_POSITION_INDEPENDENT_CODE "CMAKE_POSITION_INDEPENDENT_CODE")
If [`CMP0056`](../policy/cmp0056#policy:CMP0056 "CMP0056") is set to `NEW`, then [`CMAKE_EXE_LINKER_FLAGS`](../variable/cmake_exe_linker_flags#variable:CMAKE_EXE_LINKER_FLAGS "CMAKE_EXE_LINKER_FLAGS") is passed in as well.
The current setting of [`CMP0065`](../policy/cmp0065#policy:CMP0065 "CMP0065") is set in the generated project.
Set the [`CMAKE_TRY_COMPILE_CONFIGURATION`](../variable/cmake_try_compile_configuration#variable:CMAKE_TRY_COMPILE_CONFIGURATION "CMAKE_TRY_COMPILE_CONFIGURATION") variable to choose a build configuration.
Set the [`CMAKE_TRY_COMPILE_TARGET_TYPE`](../variable/cmake_try_compile_target_type#variable:CMAKE_TRY_COMPILE_TARGET_TYPE "CMAKE_TRY_COMPILE_TARGET_TYPE") variable to specify the type of target used for the source file signature.
Set the [`CMAKE_TRY_COMPILE_PLATFORM_VARIABLES`](../variable/cmake_try_compile_platform_variables#variable:CMAKE_TRY_COMPILE_PLATFORM_VARIABLES "CMAKE_TRY_COMPILE_PLATFORM_VARIABLES") variable to specify variables that must be propagated into the test project. This variable is meant for use only in toolchain files.
If [`CMP0067`](../policy/cmp0067#policy:CMP0067 "CMP0067") is set to `NEW`, or any of the `<LANG>_STANDARD`, `<LANG>_STANDARD_REQUIRED`, or `<LANG>_EXTENSIONS` options are used, then the language standard variables are honored:
* [`CMAKE_C_STANDARD`](../variable/cmake_c_standard#variable:CMAKE_C_STANDARD "CMAKE_C_STANDARD")
* [`CMAKE_C_STANDARD_REQUIRED`](../variable/cmake_c_standard_required#variable:CMAKE_C_STANDARD_REQUIRED "CMAKE_C_STANDARD_REQUIRED")
* [`CMAKE_C_EXTENSIONS`](../variable/cmake_c_extensions#variable:CMAKE_C_EXTENSIONS "CMAKE_C_EXTENSIONS")
* [`CMAKE_CXX_STANDARD`](../variable/cmake_cxx_standard#variable:CMAKE_CXX_STANDARD "CMAKE_CXX_STANDARD")
* [`CMAKE_CXX_STANDARD_REQUIRED`](../variable/cmake_cxx_standard_required#variable:CMAKE_CXX_STANDARD_REQUIRED "CMAKE_CXX_STANDARD_REQUIRED")
* [`CMAKE_CXX_EXTENSIONS`](../variable/cmake_cxx_extensions#variable:CMAKE_CXX_EXTENSIONS "CMAKE_CXX_EXTENSIONS")
* [`CMAKE_CUDA_STANDARD`](../variable/cmake_cuda_standard#variable:CMAKE_CUDA_STANDARD "CMAKE_CUDA_STANDARD")
* [`CMAKE_CUDA_STANDARD_REQUIRED`](../variable/cmake_cuda_standard_required#variable:CMAKE_CUDA_STANDARD_REQUIRED "CMAKE_CUDA_STANDARD_REQUIRED")
* [`CMAKE_CUDA_EXTENSIONS`](../variable/cmake_cuda_extensions#variable:CMAKE_CUDA_EXTENSIONS "CMAKE_CUDA_EXTENSIONS")
Their values are used to set the corresponding target properties in the generated project (unless overridden by an explicit option).
cmake add_subdirectory add\_subdirectory
=================
Add a subdirectory to the build.
```
add_subdirectory(source_dir [binary_dir]
[EXCLUDE_FROM_ALL])
```
Add a subdirectory to the build. The source\_dir specifies the directory in which the source CMakeLists.txt and code files are located. If it is a relative path it will be evaluated with respect to the current directory (the typical usage), but it may also be an absolute path. The `binary_dir` specifies the directory in which to place the output files. If it is a relative path it will be evaluated with respect to the current output directory, but it may also be an absolute path. If `binary_dir` is not specified, the value of `source_dir`, before expanding any relative path, will be used (the typical usage). The CMakeLists.txt file in the specified source directory will be processed immediately by CMake before processing in the current input file continues beyond this command.
If the `EXCLUDE_FROM_ALL` argument is provided then targets in the subdirectory will not be included in the `ALL` target of the parent directory by default, and will be excluded from IDE project files. Users must explicitly build targets in the subdirectory. This is meant for use when the subdirectory contains a separate part of the project that is useful but not necessary, such as a set of examples. Typically the subdirectory should contain its own [`project()`](project#command:project "project") command invocation so that a full build system will be generated in the subdirectory (such as a VS IDE solution file). Note that inter-target dependencies supercede this exclusion. If a target built by the parent project depends on a target in the subdirectory, the dependee target will be included in the parent project build system to satisfy the dependency.
cmake target_compile_definitions target\_compile\_definitions
============================
Add compile definitions to a target.
```
target_compile_definitions(<target>
<INTERFACE|PUBLIC|PRIVATE> [items1...]
[<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
```
Specify compile definitions to use when compiling a given `<target>`. The named `<target>` must have been created by a command such as [`add_executable()`](add_executable#command:add_executable "add_executable") or [`add_library()`](add_library#command:add_library "add_library") and must not be an [Imported Target](../manual/cmake-buildsystem.7#imported-targets).
The `INTERFACE`, `PUBLIC` and `PRIVATE` keywords are required to specify the scope of the following arguments. `PRIVATE` and `PUBLIC` items will populate the [`COMPILE_DEFINITIONS`](../prop_tgt/compile_definitions#prop_tgt:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") property of `<target>`. `PUBLIC` and `INTERFACE` items will populate the [`INTERFACE_COMPILE_DEFINITIONS`](../prop_tgt/interface_compile_definitions#prop_tgt:INTERFACE_COMPILE_DEFINITIONS "INTERFACE_COMPILE_DEFINITIONS") property of `<target>`. The following arguments specify compile definitions. Repeated calls for the same `<target>` append items in the order called.
Arguments to `target_compile_definitions` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake export_library_dependencies export\_library\_dependencies
=============================
Disallowed. See CMake Policy [`CMP0033`](../policy/cmp0033#policy:CMP0033 "CMP0033").
Use [`install(EXPORT)`](install#command:install "install") or [`export()`](export#command:export "export") command.
This command generates an old-style library dependencies file. Projects requiring CMake 2.6 or later should not use the command. Use instead the [`install(EXPORT)`](install#command:install "install") command to help export targets from an installation tree and the [`export()`](export#command:export "export") command to export targets from a build tree.
The old-style library dependencies file does not take into account per-configuration names of libraries or the [`LINK_INTERFACE_LIBRARIES`](../prop_tgt/link_interface_libraries#prop_tgt:LINK_INTERFACE_LIBRARIES "LINK_INTERFACE_LIBRARIES") target property.
```
export_library_dependencies(<file> [APPEND])
```
Create a file named `<file>` that can be included into a CMake listfile with the INCLUDE command. The file will contain a number of SET commands that will set all the variables needed for library dependency information. This should be the last command in the top level CMakeLists.txt file of the project. If the `APPEND` option is specified, the SET commands will be appended to the given file instead of replacing it.
cmake project project
=======
Set a name, version, and enable languages for the entire project.
```
project(<PROJECT-NAME> [LANGUAGES] [<language-name>...])
project(<PROJECT-NAME>
[VERSION <major>[.<minor>[.<patch>[.<tweak>]]]]
[DESCRIPTION <project-description-string>]
[LANGUAGES <language-name>...])
```
Sets the name of the project and stores the name in the [`PROJECT_NAME`](../variable/project_name#variable:PROJECT_NAME "PROJECT_NAME") variable. Additionally this sets variables
* [`PROJECT_SOURCE_DIR`](../variable/project_source_dir#variable:PROJECT_SOURCE_DIR "PROJECT_SOURCE_DIR"), [`<PROJECT-NAME>_SOURCE_DIR`](# "<PROJECT-NAME>_SOURCE_DIR")
* [`PROJECT_BINARY_DIR`](../variable/project_binary_dir#variable:PROJECT_BINARY_DIR "PROJECT_BINARY_DIR"), [`<PROJECT-NAME>_BINARY_DIR`](# "<PROJECT-NAME>_BINARY_DIR")
If `VERSION` is specified, given components must be non-negative integers. If `VERSION` is not specified, the default version is the empty string. The `VERSION` option may not be used unless policy [`CMP0048`](../policy/cmp0048#policy:CMP0048 "CMP0048") is set to `NEW`.
The [`project()`](#command:project "project") command stores the version number and its components in variables
* [`PROJECT_VERSION`](../variable/project_version#variable:PROJECT_VERSION "PROJECT_VERSION"), [`<PROJECT-NAME>_VERSION`](# "<PROJECT-NAME>_VERSION")
* [`PROJECT_VERSION_MAJOR`](../variable/project_version_major#variable:PROJECT_VERSION_MAJOR "PROJECT_VERSION_MAJOR"), [`<PROJECT-NAME>_VERSION_MAJOR`](# "<PROJECT-NAME>_VERSION_MAJOR")
* [`PROJECT_VERSION_MINOR`](../variable/project_version_minor#variable:PROJECT_VERSION_MINOR "PROJECT_VERSION_MINOR"), [`<PROJECT-NAME>_VERSION_MINOR`](# "<PROJECT-NAME>_VERSION_MINOR")
* [`PROJECT_VERSION_PATCH`](../variable/project_version_patch#variable:PROJECT_VERSION_PATCH "PROJECT_VERSION_PATCH"), [`<PROJECT-NAME>_VERSION_PATCH`](# "<PROJECT-NAME>_VERSION_PATCH")
* [`PROJECT_VERSION_TWEAK`](../variable/project_version_tweak#variable:PROJECT_VERSION_TWEAK "PROJECT_VERSION_TWEAK"), [`<PROJECT-NAME>_VERSION_TWEAK`](# "<PROJECT-NAME>_VERSION_TWEAK")
Variables corresponding to unspecified versions are set to the empty string (if policy [`CMP0048`](../policy/cmp0048#policy:CMP0048 "CMP0048") is set to `NEW`).
If optional `DESCRIPTION` is given, then additional [`PROJECT_DESCRIPTION`](../variable/project_description#variable:PROJECT_DESCRIPTION "PROJECT_DESCRIPTION") variable will be set to its argument. The argument must be a string with short description of the project (only a few words).
Optionally you can specify which languages your project supports. Example languages are `C`, `CXX` (i.e. C++), `Fortran`, etc. By default `C` and `CXX` are enabled if no language options are given. Specify language `NONE`, or use the `LANGUAGES` keyword and list no languages, to skip enabling any languages.
If a variable exists called [`CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE`](# "CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE"), the file pointed to by that variable will be included as the last step of the project command.
The top-level `CMakeLists.txt` file for a project must contain a literal, direct call to the [`project()`](#command:project "project") command; loading one through the [`include()`](include#command:include "include") command is not sufficient. If no such call exists CMake will implicitly add one to the top that enables the default languages (`C` and `CXX`).
Note
Call the [`cmake_minimum_required()`](cmake_minimum_required#command:cmake_minimum_required "cmake_minimum_required") command at the beginning of the top-level `CMakeLists.txt` file even before calling the `project()` command. It is important to establish version and policy settings before invoking other commands whose behavior they may affect. See also policy [`CMP0000`](../policy/cmp0000#policy:CMP0000 "CMP0000").
| programming_docs |
cmake add_definitions add\_definitions
================
Adds -D define flags to the compilation of source files.
```
add_definitions(-DFOO -DBAR ...)
```
Adds definitions to the compiler command line for targets in the current directory and below (whether added before or after this command is invoked). This command can be used to add any flags, but it is intended to add preprocessor definitions (see the [`add_compile_options()`](add_compile_options#command:add_compile_options "add_compile_options") command to add other flags). Flags beginning in -D or /D that look like preprocessor definitions are automatically added to the [`COMPILE_DEFINITIONS`](../prop_dir/compile_definitions#prop_dir:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") directory property for the current directory. Definitions with non-trivial values may be left in the set of flags instead of being converted for reasons of backwards compatibility. See documentation of the [`directory`](../prop_dir/compile_definitions#prop_dir:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS"), [`target`](../prop_tgt/compile_definitions#prop_tgt:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS"), [`source file`](../prop_sf/compile_definitions#prop_sf:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") `COMPILE_DEFINITIONS` properties for details on adding preprocessor definitions to specific scopes and configurations.
See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
cmake separate_arguments separate\_arguments
===================
Parse space-separated arguments into a semicolon-separated list.
```
separate_arguments(<var> <NATIVE|UNIX|WINDOWS>_COMMAND "<args>")
```
Parses a UNIX- or Windows-style command-line string “<args>” and stores a semicolon-separated list of the arguments in `<var>`. The entire command line must be given in one “<args>” argument.
The `UNIX_COMMAND` mode separates arguments by unquoted whitespace. It recognizes both single-quote and double-quote pairs. A backslash escapes the next literal character (`\"` is `"`); there are no special escapes (`\n` is just `n`).
The `WINDOWS_COMMAND` mode parses a Windows command-line using the same syntax the runtime library uses to construct argv at startup. It separates arguments by whitespace that is not double-quoted. Backslashes are literal unless they precede double-quotes. See the MSDN article [Parsing C Command-Line Arguments](https://msdn.microsoft.com/library/a1y7w461.aspx) for details.
The `NATIVE_COMMAND` mode parses a Windows command-line if the host system is Windows, and a UNIX command-line otherwise.
```
separate_arguments(<var>)
```
Convert the value of `<var>` to a semi-colon separated list. All spaces are replaced with ‘;’. This helps with generating command lines.
cmake add_library add\_library
============
* [Normal Libraries](#normal-libraries)
* [Imported Libraries](#imported-libraries)
* [Object Libraries](#object-libraries)
* [Alias Libraries](#alias-libraries)
* [Interface Libraries](#interface-libraries)
Add a library to the project using the specified source files.
Normal Libraries
----------------
```
add_library(<name> [STATIC | SHARED | MODULE]
[EXCLUDE_FROM_ALL]
source1 [source2 ...])
```
Adds a library target called `<name>` to be built from the source files listed in the command invocation. The `<name>` corresponds to the logical target name and must be globally unique within a project. The actual file name of the library built is constructed based on conventions of the native platform (such as `lib<name>.a` or `<name>.lib`).
`STATIC`, `SHARED`, or `MODULE` may be given to specify the type of library to be created. `STATIC` libraries are archives of object files for use when linking other targets. `SHARED` libraries are linked dynamically and loaded at runtime. `MODULE` libraries are plugins that are not linked into other targets but may be loaded dynamically at runtime using dlopen-like functionality. If no type is given explicitly the type is `STATIC` or `SHARED` based on whether the current value of the variable [`BUILD_SHARED_LIBS`](../variable/build_shared_libs#variable:BUILD_SHARED_LIBS "BUILD_SHARED_LIBS") is `ON`. For `SHARED` and `MODULE` libraries the [`POSITION_INDEPENDENT_CODE`](../prop_tgt/position_independent_code#prop_tgt:POSITION_INDEPENDENT_CODE "POSITION_INDEPENDENT_CODE") target property is set to `ON` automatically. A `SHARED` or `STATIC` library may be marked with the [`FRAMEWORK`](../prop_tgt/framework#prop_tgt:FRAMEWORK "FRAMEWORK") target property to create an OS X Framework.
If a library does not export any symbols, it must not be declared as a `SHARED` library. For example, a Windows resource DLL or a managed C++/CLI DLL that exports no unmanaged symbols would need to be a `MODULE` library. This is because CMake expects a `SHARED` library to always have an associated import library on Windows.
By default the library file will be created in the build tree directory corresponding to the source tree directory in which the command was invoked. See documentation of the [`ARCHIVE_OUTPUT_DIRECTORY`](../prop_tgt/archive_output_directory#prop_tgt:ARCHIVE_OUTPUT_DIRECTORY "ARCHIVE_OUTPUT_DIRECTORY"), [`LIBRARY_OUTPUT_DIRECTORY`](../prop_tgt/library_output_directory#prop_tgt:LIBRARY_OUTPUT_DIRECTORY "LIBRARY_OUTPUT_DIRECTORY"), and [`RUNTIME_OUTPUT_DIRECTORY`](../prop_tgt/runtime_output_directory#prop_tgt:RUNTIME_OUTPUT_DIRECTORY "RUNTIME_OUTPUT_DIRECTORY") target properties to change this location. See documentation of the [`OUTPUT_NAME`](../prop_tgt/output_name#prop_tgt:OUTPUT_NAME "OUTPUT_NAME") target property to change the `<name>` part of the final file name.
If `EXCLUDE_FROM_ALL` is given the corresponding property will be set on the created target. See documentation of the [`EXCLUDE_FROM_ALL`](../prop_tgt/exclude_from_all#prop_tgt:EXCLUDE_FROM_ALL "EXCLUDE_FROM_ALL") target property for details.
Source arguments to `add_library` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
See also [`HEADER_FILE_ONLY`](../prop_sf/header_file_only#prop_sf:HEADER_FILE_ONLY "HEADER_FILE_ONLY") on what to do if some sources are pre-processed, and you want to have the original sources reachable from within IDE.
Imported Libraries
------------------
```
add_library(<name> <SHARED|STATIC|MODULE|OBJECT|UNKNOWN> IMPORTED
[GLOBAL])
```
An [IMPORTED library target](../manual/cmake-buildsystem.7#imported-targets) references a library file located outside the project. No rules are generated to build it, and the [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target property is `True`. The target name has scope in the directory in which it is created and below, but the `GLOBAL` option extends visibility. It may be referenced like any target built within the project. `IMPORTED` libraries are useful for convenient reference from commands like [`target_link_libraries()`](target_link_libraries#command:target_link_libraries "target_link_libraries"). Details about the imported library are specified by setting properties whose names begin in `IMPORTED_` and `INTERFACE_`. The most important such property is [`IMPORTED_LOCATION`](../prop_tgt/imported_location#prop_tgt:IMPORTED_LOCATION "IMPORTED_LOCATION") (and its per-configuration variant [`IMPORTED_LOCATION_<CONFIG>`](# "IMPORTED_LOCATION_<CONFIG>")) which specifies the location of the main library file on disk. See documentation of the `IMPORTED_*` and `INTERFACE_*` properties for more information.
Object Libraries
----------------
```
add_library(<name> OBJECT <src>...)
```
Creates an [Object Library](../manual/cmake-buildsystem.7#object-libraries). An object library compiles source files but does not archive or link their object files into a library. Instead other targets created by [`add_library()`](#command:add_library "add_library") or [`add_executable()`](add_executable#command:add_executable "add_executable") may reference the objects using an expression of the form `$<TARGET_OBJECTS:objlib>` as a source, where `objlib` is the object library name. For example:
```
add_library(... $<TARGET_OBJECTS:objlib> ...)
add_executable(... $<TARGET_OBJECTS:objlib> ...)
```
will include objlib’s object files in a library and an executable along with those compiled from their own sources. Object libraries may contain only sources that compile, header files, and other files that would not affect linking of a normal library (e.g. `.txt`). They may contain custom commands generating such sources, but not `PRE_BUILD`, `PRE_LINK`, or `POST_BUILD` commands. Object libraries cannot be linked. Some native build systems may not like targets that have only object files, so consider adding at least one real source file to any target that references `$<TARGET_OBJECTS:objlib>`.
Alias Libraries
---------------
```
add_library(<name> ALIAS <target>)
```
Creates an [Alias Target](../manual/cmake-buildsystem.7#alias-targets), such that `<name>` can be used to refer to `<target>` in subsequent commands. The `<name>` does not appear in the generated buildsystem as a make target. The `<target>` may not be an [Imported Target](../manual/cmake-buildsystem.7#imported-targets) or an `ALIAS`. `ALIAS` targets can be used as linkable targets and as targets to read properties from. They can also be tested for existence with the regular [`if(TARGET)`](if#command:if "if") subcommand. The `<name>` may not be used to modify properties of `<target>`, that is, it may not be used as the operand of [`set_property()`](set_property#command:set_property "set_property"), [`set_target_properties()`](set_target_properties#command:set_target_properties "set_target_properties"), [`target_link_libraries()`](target_link_libraries#command:target_link_libraries "target_link_libraries") etc. An `ALIAS` target may not be installed or exported.
Interface Libraries
-------------------
```
add_library(<name> INTERFACE [IMPORTED [GLOBAL]])
```
Creates an [Interface Library](../manual/cmake-buildsystem.7#interface-libraries). An `INTERFACE` library target does not directly create build output, though it may have properties set on it and it may be installed, exported and imported. Typically the `INTERFACE_*` properties are populated on the interface target using the commands:
* [`set_property()`](set_property#command:set_property "set_property"),
* [`target_link_libraries(INTERFACE)`](target_link_libraries#command:target_link_libraries "target_link_libraries"),
* [`target_include_directories(INTERFACE)`](target_include_directories#command:target_include_directories "target_include_directories"),
* [`target_compile_options(INTERFACE)`](target_compile_options#command:target_compile_options "target_compile_options"),
* [`target_compile_definitions(INTERFACE)`](target_compile_definitions#command:target_compile_definitions "target_compile_definitions"), and
* [`target_sources(INTERFACE)`](target_sources#command:target_sources "target_sources"),
and then it is used as an argument to [`target_link_libraries()`](target_link_libraries#command:target_link_libraries "target_link_libraries") like any other target.
An `INTERFACE` [Imported Target](../manual/cmake-buildsystem.7#imported-targets) may also be created with this signature. An `IMPORTED` library target references a library defined outside the project. The target name has scope in the directory in which it is created and below, but the `GLOBAL` option extends visibility. It may be referenced like any target built within the project. `IMPORTED` libraries are useful for convenient reference from commands like [`target_link_libraries()`](target_link_libraries#command:target_link_libraries "target_link_libraries").
cmake return return
======
Return from a file, directory or function.
```
return()
```
Returns from a file, directory or function. When this command is encountered in an included file (via [`include()`](include#command:include "include") or [`find_package()`](find_package#command:find_package "find_package")), it causes processing of the current file to stop and control is returned to the including file. If it is encountered in a file which is not included by another file, e.g. a `CMakeLists.txt`, control is returned to the parent directory if there is one. If return is called in a function, control is returned to the caller of the function. Note that a macro is not a function and does not handle return like a function does.
cmake site_name site\_name
==========
Set the given variable to the name of the computer.
```
site_name(variable)
```
cmake define_property define\_property
================
Define and document custom properties.
```
define_property(<GLOBAL | DIRECTORY | TARGET | SOURCE |
TEST | VARIABLE | CACHED_VARIABLE>
PROPERTY <name> [INHERITED]
BRIEF_DOCS <brief-doc> [docs...]
FULL_DOCS <full-doc> [docs...])
```
Define one property in a scope for use with the [`set_property()`](set_property#command:set_property "set_property") and [`get_property()`](get_property#command:get_property "get_property") commands. This is primarily useful to associate documentation with property names that may be retrieved with the [`get_property()`](get_property#command:get_property "get_property") command. The first argument determines the kind of scope in which the property should be used. It must be one of the following:
```
GLOBAL = associated with the global namespace
DIRECTORY = associated with one directory
TARGET = associated with one target
SOURCE = associated with one source file
TEST = associated with a test named with add_test
VARIABLE = documents a CMake language variable
CACHED_VARIABLE = documents a CMake cache variable
```
Note that unlike [`set_property()`](set_property#command:set_property "set_property") and [`get_property()`](get_property#command:get_property "get_property") no actual scope needs to be given; only the kind of scope is important.
The required `PROPERTY` option is immediately followed by the name of the property being defined.
If the `INHERITED` option then the [`get_property()`](get_property#command:get_property "get_property") command will chain up to the next higher scope when the requested property is not set in the scope given to the command. `DIRECTORY` scope chains to `GLOBAL`. `TARGET`, `SOURCE`, and `TEST` chain to `DIRECTORY`.
The `BRIEF_DOCS` and `FULL_DOCS` options are followed by strings to be associated with the property as its brief and full documentation. Corresponding options to the [`get_property()`](get_property#command:get_property "get_property") command will retrieve the documentation.
cmake add_executable add\_executable
===============
Add an executable to the project using the specified source files.
```
add_executable(<name> [WIN32] [MACOSX_BUNDLE]
[EXCLUDE_FROM_ALL]
source1 [source2 ...])
```
Adds an executable target called `<name>` to be built from the source files listed in the command invocation. The `<name>` corresponds to the logical target name and must be globally unique within a project. The actual file name of the executable built is constructed based on conventions of the native platform (such as `<name>.exe` or just `<name>`).
By default the executable file will be created in the build tree directory corresponding to the source tree directory in which the command was invoked. See documentation of the [`RUNTIME_OUTPUT_DIRECTORY`](../prop_tgt/runtime_output_directory#prop_tgt:RUNTIME_OUTPUT_DIRECTORY "RUNTIME_OUTPUT_DIRECTORY") target property to change this location. See documentation of the [`OUTPUT_NAME`](../prop_tgt/output_name#prop_tgt:OUTPUT_NAME "OUTPUT_NAME") target property to change the `<name>` part of the final file name.
If `WIN32` is given the property [`WIN32_EXECUTABLE`](../prop_tgt/win32_executable#prop_tgt:WIN32_EXECUTABLE "WIN32_EXECUTABLE") will be set on the target created. See documentation of that target property for details.
If `MACOSX_BUNDLE` is given the corresponding property will be set on the created target. See documentation of the [`MACOSX_BUNDLE`](../prop_tgt/macosx_bundle#prop_tgt:MACOSX_BUNDLE "MACOSX_BUNDLE") target property for details.
If `EXCLUDE_FROM_ALL` is given the corresponding property will be set on the created target. See documentation of the [`EXCLUDE_FROM_ALL`](../prop_tgt/exclude_from_all#prop_tgt:EXCLUDE_FROM_ALL "EXCLUDE_FROM_ALL") target property for details.
Source arguments to `add_executable` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-buildsystem(7)`](../manual/cmake-buildsystem.7#manual:cmake-buildsystem(7) "cmake-buildsystem(7)") manual for more on defining buildsystem properties.
See also [`HEADER_FILE_ONLY`](../prop_sf/header_file_only#prop_sf:HEADER_FILE_ONLY "HEADER_FILE_ONLY") on what to do if some sources are pre-processed, and you want to have the original sources reachable from within IDE.
```
add_executable(<name> IMPORTED [GLOBAL])
```
An [IMPORTED executable target](../manual/cmake-buildsystem.7#imported-targets) references an executable file located outside the project. No rules are generated to build it, and the [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target property is `True`. The target name has scope in the directory in which it is created and below, but the `GLOBAL` option extends visibility. It may be referenced like any target built within the project. `IMPORTED` executables are useful for convenient reference from commands like [`add_custom_command()`](add_custom_command#command:add_custom_command "add_custom_command"). Details about the imported executable are specified by setting properties whose names begin in `IMPORTED_`. The most important such property is [`IMPORTED_LOCATION`](../prop_tgt/imported_location#prop_tgt:IMPORTED_LOCATION "IMPORTED_LOCATION") (and its per-configuration version [`IMPORTED_LOCATION_<CONFIG>`](# "IMPORTED_LOCATION_<CONFIG>")) which specifies the location of the main executable file on disk. See documentation of the `IMPORTED_*` properties for more information.
```
add_executable(<name> ALIAS <target>)
```
Creates an [Alias Target](../manual/cmake-buildsystem.7#alias-targets), such that `<name>` can be used to refer to `<target>` in subsequent commands. The `<name>` does not appear in the generated buildsystem as a make target. The `<target>` may not be an [Imported Target](../manual/cmake-buildsystem.7#imported-targets) or an `ALIAS`. `ALIAS` targets can be used as targets to read properties from, executables for custom commands and custom targets. They can also be tested for existence with the regular [`if(TARGET)`](if#command:if "if") subcommand. The `<name>` may not be used to modify properties of `<target>`, that is, it may not be used as the operand of [`set_property()`](set_property#command:set_property "set_property"), [`set_target_properties()`](set_target_properties#command:set_target_properties "set_target_properties"), [`target_link_libraries()`](target_link_libraries#command:target_link_libraries "target_link_libraries") etc. An `ALIAS` target may not be installed or exported.
cmake try_run try\_run
========
* [Try Compiling and Running Source Files](#try-compiling-and-running-source-files)
* [Other Behavior Settings](#other-behavior-settings)
* [Behavior when Cross Compiling](#behavior-when-cross-compiling)
Try compiling and then running some code.
Try Compiling and Running Source Files
--------------------------------------
```
try_run(RUN_RESULT_VAR COMPILE_RESULT_VAR
bindir srcfile [CMAKE_FLAGS <flags>...]
[COMPILE_DEFINITIONS <defs>...]
[LINK_LIBRARIES <libs>...]
[COMPILE_OUTPUT_VARIABLE <var>]
[RUN_OUTPUT_VARIABLE <var>]
[OUTPUT_VARIABLE <var>]
[ARGS <args>...])
```
Try compiling a `<srcfile>`. Returns `TRUE` or `FALSE` for success or failure in `COMPILE_RESULT_VAR`. If the compile succeeded, runs the executable and returns its exit code in `RUN_RESULT_VAR`. If the executable was built, but failed to run, then `RUN_RESULT_VAR` will be set to `FAILED_TO_RUN`. See the [`try_compile()`](try_compile#command:try_compile "try_compile") command for information on how the test project is constructed to build the source file.
The options are:
`CMAKE_FLAGS <flags>...` Specify flags of the form `-DVAR:TYPE=VALUE` to be passed to the `cmake` command-line used to drive the test build. The example in [`try_compile()`](try_compile#command:try_compile "try_compile") shows how values for variables `INCLUDE_DIRECTORIES`, `LINK_DIRECTORIES`, and `LINK_LIBRARIES` are used.
`COMPILE_DEFINITIONS <defs>...` Specify `-Ddefinition` arguments to pass to `add_definitions` in the generated test project.
`COMPILE_OUTPUT_VARIABLE <var>` Report the compile step build output in a given variable.
`LINK_LIBRARIES <libs>...`
Specify libraries to be linked in the generated project. The list of libraries may refer to system libraries and to [Imported Targets](../manual/cmake-buildsystem.7#imported-targets) from the calling project.
If this option is specified, any `-DLINK_LIBRARIES=...` value given to the `CMAKE_FLAGS` option will be ignored.
`OUTPUT_VARIABLE <var>` Report the compile build output and the output from running the executable in the given variable. This option exists for legacy reasons. Prefer `COMPILE_OUTPUT_VARIABLE` and `RUN_OUTPUT_VARIABLE` instead.
`RUN_OUTPUT_VARIABLE <var>` Report the output from running the executable in a given variable. Other Behavior Settings
-----------------------
Set the [`CMAKE_TRY_COMPILE_CONFIGURATION`](../variable/cmake_try_compile_configuration#variable:CMAKE_TRY_COMPILE_CONFIGURATION "CMAKE_TRY_COMPILE_CONFIGURATION") variable to choose a build configuration.
Behavior when Cross Compiling
-----------------------------
When cross compiling, the executable compiled in the first step usually cannot be run on the build host. The `try_run` command checks the [`CMAKE_CROSSCOMPILING`](../variable/cmake_crosscompiling#variable:CMAKE_CROSSCOMPILING "CMAKE_CROSSCOMPILING") variable to detect whether CMake is in cross-compiling mode. If that is the case, it will still try to compile the executable, but it will not try to run the executable unless the [`CMAKE_CROSSCOMPILING_EMULATOR`](../variable/cmake_crosscompiling_emulator#variable:CMAKE_CROSSCOMPILING_EMULATOR "CMAKE_CROSSCOMPILING_EMULATOR") variable is set. Instead it will create cache variables which must be filled by the user or by presetting them in some CMake script file to the values the executable would have produced if it had been run on its actual target platform. These cache entries are:
`<RUN_RESULT_VAR>` Exit code if the executable were to be run on the target platform.
`<RUN_RESULT_VAR>__TRYRUN_OUTPUT` Output from stdout and stderr if the executable were to be run on the target platform. This is created only if the `RUN_OUTPUT_VARIABLE` or `OUTPUT_VARIABLE` option was used. In order to make cross compiling your project easier, use `try_run` only if really required. If you use `try_run`, use the `RUN_OUTPUT_VARIABLE` or `OUTPUT_VARIABLE` options only if really required. Using them will require that when cross-compiling, the cache variables will have to be set manually to the output of the executable. You can also “guard” the calls to `try_run` with an [`if()`](if#command:if "if") block checking the [`CMAKE_CROSSCOMPILING`](../variable/cmake_crosscompiling#variable:CMAKE_CROSSCOMPILING "CMAKE_CROSSCOMPILING") variable and provide an easy-to-preset alternative for this case.
| programming_docs |
cmake get_source_file_property get\_source\_file\_property
===========================
Get a property for a source file.
```
get_source_file_property(VAR file property)
```
Get a property from a source file. The value of the property is stored in the variable `VAR`. If the property is not found, `VAR` will be set to “NOTFOUND”. Use [`set_source_files_properties()`](set_source_files_properties#command:set_source_files_properties "set_source_files_properties") to set property values. Source file properties usually control how the file is built. One property that is always there is [`LOCATION`](../prop_sf/location#prop_sf:LOCATION "LOCATION")
See also the more general [`get_property()`](get_property#command:get_property "get_property") command.
cmake target_compile_features target\_compile\_features
=========================
Add expected compiler features to a target.
```
target_compile_features(<target> <PRIVATE|PUBLIC|INTERFACE> <feature> [...])
```
Specify compiler features required when compiling a given target. If the feature is not listed in the [`CMAKE_C_COMPILE_FEATURES`](../variable/cmake_c_compile_features#variable:CMAKE_C_COMPILE_FEATURES "CMAKE_C_COMPILE_FEATURES") variable or [`CMAKE_CXX_COMPILE_FEATURES`](../variable/cmake_cxx_compile_features#variable:CMAKE_CXX_COMPILE_FEATURES "CMAKE_CXX_COMPILE_FEATURES") variable, then an error will be reported by CMake. If the use of the feature requires an additional compiler flag, such as `-std=gnu++11`, the flag will be added automatically.
The `INTERFACE`, `PUBLIC` and `PRIVATE` keywords are required to specify the scope of the features. `PRIVATE` and `PUBLIC` items will populate the [`COMPILE_FEATURES`](../prop_tgt/compile_features#prop_tgt:COMPILE_FEATURES "COMPILE_FEATURES") property of `<target>`. `PUBLIC` and `INTERFACE` items will populate the [`INTERFACE_COMPILE_FEATURES`](../prop_tgt/interface_compile_features#prop_tgt:INTERFACE_COMPILE_FEATURES "INTERFACE_COMPILE_FEATURES") property of `<target>`. Repeated calls for the same `<target>` append items.
The named `<target>` must have been created by a command such as [`add_executable()`](add_executable#command:add_executable "add_executable") or [`add_library()`](add_library#command:add_library "add_library") and must not be an `IMPORTED` target.
Arguments to `target_compile_features` may use “generator expressions” with the syntax `$<...>`. See the [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") manual for available expressions. See the [`cmake-compile-features(7)`](../manual/cmake-compile-features.7#manual:cmake-compile-features(7) "cmake-compile-features(7)") manual for information on compile features and a list of supported compilers.
cmake math math
====
Mathematical expressions.
```
math(EXPR <output-variable> <math-expression>)
```
`EXPR` evaluates mathematical expression and returns result in the output variable. Example mathematical expression is `5 * (10 + 13)`. Supported operators are `+`, `-`, `*`, `/`, `%`, `|`, `&`, `^`, `~`, `<<`, `>>`, and `(...)`. They have the same meaning as they do in C code.
cmake export export
======
Export targets from the build tree for use by outside projects.
```
export(EXPORT <export-name> [NAMESPACE <namespace>] [FILE <filename>])
```
Create a file `<filename>` that may be included by outside projects to import targets from the current project’s build tree. This is useful during cross-compiling to build utility executables that can run on the host platform in one project and then import them into another project being compiled for the target platform. If the `NAMESPACE` option is given the `<namespace>` string will be prepended to all target names written to the file.
Target installations are associated with the export `<export-name>` using the `EXPORT` option of the [`install(TARGETS)`](install#command:install "install") command.
The file created by this command is specific to the build tree and should never be installed. See the [`install(EXPORT)`](install#command:install "install") command to export targets from an installation tree.
The properties set on the generated IMPORTED targets will have the same values as the final values of the input TARGETS.
```
export(TARGETS [target1 [target2 [...]]] [NAMESPACE <namespace>]
[APPEND] FILE <filename> [EXPORT_LINK_INTERFACE_LIBRARIES])
```
This signature is similar to the `EXPORT` signature, but targets are listed explicitly rather than specified as an export-name. If the APPEND option is given the generated code will be appended to the file instead of overwriting it. The EXPORT\_LINK\_INTERFACE\_LIBRARIES keyword, if present, causes the contents of the properties matching `(IMPORTED_)?LINK_INTERFACE_LIBRARIES(_<CONFIG>)?` to be exported, when policy CMP0022 is NEW. If a library target is included in the export but a target to which it links is not included the behavior is unspecified.
```
export(PACKAGE <name>)
```
Store the current build directory in the CMake user package registry for package `<name>`. The find\_package command may consider the directory while searching for package `<name>`. This helps dependent projects find and use a package from the current project’s build tree without help from the user. Note that the entry in the package registry that this command creates works only in conjunction with a package configuration file (`<name>Config.cmake`) that works with the build tree. In some cases, for example for packaging and for system wide installations, it is not desirable to write the user package registry. If the [`CMAKE_EXPORT_NO_PACKAGE_REGISTRY`](../variable/cmake_export_no_package_registry#variable:CMAKE_EXPORT_NO_PACKAGE_REGISTRY "CMAKE_EXPORT_NO_PACKAGE_REGISTRY") variable is enabled, the `export(PACKAGE)` command will do nothing.
```
export(TARGETS [target1 [target2 [...]]] [ANDROID_MK <filename>])
```
This signature exports cmake built targets to the android ndk build system by creating an Android.mk file that references the prebuilt targets. The Android NDK supports the use of prebuilt libraries, both static and shared. This allows cmake to build the libraries of a project and make them available to an ndk build system complete with transitive dependencies, include flags and defines required to use the libraries. The signature takes a list of targets and puts them in the Android.mk file specified by the `<filename>` given. This signature can only be used if policy CMP0022 is NEW for all targets given. A error will be issued if that policy is set to OLD for one of the targets.
cmake endif endif
=====
Ends a list of commands in an if block.
```
endif(expression)
```
See the [`if()`](if#command:if "if") command.
cmake endwhile endwhile
========
Ends a list of commands in a while block.
```
endwhile(expression)
```
See the [`while()`](while#command:while "while") command.
cmake ctest_run_script ctest\_run\_script
==================
runs a ctest -S script
```
ctest_run_script([NEW_PROCESS] script_file_name script_file_name1
script_file_name2 ... [RETURN_VALUE var])
```
Runs a script or scripts much like if it was run from ctest -S. If no argument is provided then the current script is run using the current settings of the variables. If `NEW_PROCESS` is specified then each script will be run in a separate process.If `RETURN_VALUE` is specified the return value of the last script run will be put into `var`.
cmake break break
=====
Break from an enclosing foreach or while loop.
```
break()
```
Breaks from an enclosing foreach loop or while loop
See also the [`continue()`](continue#command:continue "continue") command.
cmake load_command load\_command
=============
Disallowed. See CMake Policy [`CMP0031`](../policy/cmp0031#policy:CMP0031 "CMP0031").
Load a command into a running CMake.
```
load_command(COMMAND_NAME <loc1> [loc2 ...])
```
The given locations are searched for a library whose name is cmCOMMAND\_NAME. If found, it is loaded as a module and the command is added to the set of available CMake commands. Usually, [`try_compile()`](try_compile#command:try_compile "try_compile") is used before this command to compile the module. If the command is successfully loaded a variable named
```
CMAKE_LOADED_COMMAND_<COMMAND_NAME>
```
will be set to the full path of the module that was loaded. Otherwise the variable will not be set.
cmake enable_testing enable\_testing
===============
Enable testing for current directory and below.
```
enable_testing()
```
Enables testing for this directory and below. See also the [`add_test()`](add_test#command:add_test "add_test") command. Note that ctest expects to find a test file in the build directory root. Therefore, this command should be in the source directory root.
cmake set set
===
Set a normal, cache, or environment variable to a given value. See the [cmake-language(7) variables](../manual/cmake-language.7#cmake-language-variables) documentation for the scopes and interaction of normal variables and cache entries.
Signatures of this command that specify a `<value>...` placeholder expect zero or more arguments. Multiple arguments will be joined as a [;-list](../manual/cmake-language.7#cmake-language-lists) to form the actual variable value to be set. Zero arguments will cause normal variables to be unset. See the [`unset()`](unset#command:unset "unset") command to unset variables explicitly.
Set Normal Variable
-------------------
```
set(<variable> <value>... [PARENT_SCOPE])
```
Set the given `<variable>` in the current function or directory scope.
If the `PARENT_SCOPE` option is given the variable will be set in the scope above the current scope. Each new directory or function creates a new scope. This command will set the value of a variable into the parent directory or calling function (whichever is applicable to the case at hand). The previous state of the variable’s value stays the same in the current scope (e.g., if it was undefined before, it is still undefined and if it had a value, it is still that value).
Set Cache Entry
---------------
```
set(<variable> <value>... CACHE <type> <docstring> [FORCE])
```
Set the given cache `<variable>` (cache entry). Since cache entries are meant to provide user-settable values this does not overwrite existing cache entries by default. Use the `FORCE` option to overwrite existing entries.
The `<type>` must be specified as one of:
`BOOL` Boolean `ON/OFF` value. [`cmake-gui(1)`](../manual/cmake-gui.1#manual:cmake-gui(1) "cmake-gui(1)") offers a checkbox.
`FILEPATH` Path to a file on disk. [`cmake-gui(1)`](../manual/cmake-gui.1#manual:cmake-gui(1) "cmake-gui(1)") offers a file dialog.
`PATH` Path to a directory on disk. [`cmake-gui(1)`](../manual/cmake-gui.1#manual:cmake-gui(1) "cmake-gui(1)") offers a file dialog.
`STRING` A line of text. [`cmake-gui(1)`](../manual/cmake-gui.1#manual:cmake-gui(1) "cmake-gui(1)") offers a text field or a drop-down selection if the [`STRINGS`](../prop_cache/strings#prop_cache:STRINGS "STRINGS") cache entry property is set.
`INTERNAL` A line of text. [`cmake-gui(1)`](../manual/cmake-gui.1#manual:cmake-gui(1) "cmake-gui(1)") does not show internal entries. They may be used to store variables persistently across runs. Use of this type implies `FORCE`. The `<docstring>` must be specified as a line of text providing a quick summary of the option for presentation to [`cmake-gui(1)`](../manual/cmake-gui.1#manual:cmake-gui(1) "cmake-gui(1)") users.
If the cache entry does not exist prior to the call or the `FORCE` option is given then the cache entry will be set to the given value. Furthermore, any normal variable binding in the current scope will be removed to expose the newly cached value to any immediately following evaluation.
It is possible for the cache entry to exist prior to the call but have no type set if it was created on the [`cmake(1)`](../manual/cmake.1#manual:cmake(1) "cmake(1)") command line by a user through the `-D<var>=<value>` option without specifying a type. In this case the `set` command will add the type. Furthermore, if the `<type>` is `PATH` or `FILEPATH` and the `<value>` provided on the command line is a relative path, then the `set` command will treat the path as relative to the current working directory and convert it to an absolute path.
Set Environment Variable
------------------------
```
set(ENV{<variable>} <value>...)
```
Set the current process environment `<variable>` to the given value.
cmake if if
==
Conditionally execute a group of commands.
```
if(expression)
# then section.
COMMAND1(ARGS ...)
COMMAND2(ARGS ...)
#...
elseif(expression2)
# elseif section.
COMMAND1(ARGS ...)
COMMAND2(ARGS ...)
#...
else(expression)
# else section.
COMMAND1(ARGS ...)
COMMAND2(ARGS ...)
#...
endif(expression)
```
Evaluates the given expression. If the result is true, the commands in the THEN section are invoked. Otherwise, the commands in the else section are invoked. The elseif and else sections are optional. You may have multiple elseif clauses. Note that the expression in the else and endif clause is optional. Long expressions can be used and there is a traditional order of precedence. Parenthetical expressions are evaluated first followed by unary tests such as `EXISTS`, `COMMAND`, and `DEFINED`. Then any binary tests such as `EQUAL`, `LESS`, `LESS_EQUAL, ``GREATER`, `GREATER_EQUAL`, `STREQUAL`, `STRLESS`, `STRLESS_EQUAL`, `STRGREATER`, `STRGREATER_EQUAL`, `VERSION_EQUAL`, `VERSION_LESS`, `VERSION_LESS_EQUAL`, `VERSION_GREATER`, `VERSION_GREATER_EQUAL`, and `MATCHES` will be evaluated. Then boolean `NOT` operators and finally boolean `AND` and then `OR` operators will be evaluated.
Possible expressions are:
`if(<constant>)` True if the constant is `1`, `ON`, `YES`, `TRUE`, `Y`, or a non-zero number. False if the constant is `0`, `OFF`, `NO`, `FALSE`, `N`, `IGNORE`, `NOTFOUND`, the empty string, or ends in the suffix `-NOTFOUND`. Named boolean constants are case-insensitive. If the argument is not one of these specific constants, it is treated as a variable or string and the following signature is used.
`if(<variable|string>)` True if given a variable that is defined to a value that is not a false constant. False otherwise. (Note macro arguments are not variables.)
`if(NOT <expression>)` True if the expression is not true.
`if(<expr1> AND <expr2>)` True if both expressions would be considered true individually.
`if(<expr1> OR <expr2>)` True if either expression would be considered true individually.
`if(COMMAND command-name)` True if the given name is a command, macro or function that can be invoked.
`if(POLICY policy-id)` True if the given name is an existing policy (of the form `CMP<NNNN>`).
`if(TARGET target-name)` True if the given name is an existing logical target name created by a call to the [`add_executable()`](add_executable#command:add_executable "add_executable"), [`add_library()`](add_library#command:add_library "add_library"), or [`add_custom_target()`](add_custom_target#command:add_custom_target "add_custom_target") command that has already been invoked (in any directory).
`if(TEST test-name)` True if the given name is an existing test name created by the [`add_test()`](add_test#command:add_test "add_test") command.
`if(EXISTS path-to-file-or-directory)` True if the named file or directory exists. Behavior is well-defined only for full paths.
`if(file1 IS_NEWER_THAN file2)` True if `file1` is newer than `file2` or if one of the two files doesn’t exist. Behavior is well-defined only for full paths. If the file time stamps are exactly the same, an `IS_NEWER_THAN` comparison returns true, so that any dependent build operations will occur in the event of a tie. This includes the case of passing the same file name for both file1 and file2.
`if(IS_DIRECTORY path-to-directory)` True if the given name is a directory. Behavior is well-defined only for full paths.
`if(IS_SYMLINK file-name)` True if the given name is a symbolic link. Behavior is well-defined only for full paths.
`if(IS_ABSOLUTE path)` True if the given path is an absolute path.
`if(<variable|string> MATCHES regex)` True if the given string or variable’s value matches the given regular expression. See [Regex Specification](string#regex-specification) for regex format. `()` groups are captured in [`CMAKE_MATCH_<n>`](# "CMAKE_MATCH_<n>") variables.
`if(<variable|string> LESS <variable|string>)` True if the given string or variable’s value is a valid number and less than that on the right.
`if(<variable|string> GREATER <variable|string>)` True if the given string or variable’s value is a valid number and greater than that on the right.
`if(<variable|string> EQUAL <variable|string>)` True if the given string or variable’s value is a valid number and equal to that on the right.
`if(<variable|string> LESS_EQUAL <variable|string>)` True if the given string or variable’s value is a valid number and less than or equal to that on the right.
`if(<variable|string> GREATER_EQUAL <variable|string>)` True if the given string or variable’s value is a valid number and greater than or equal to that on the right.
`if(<variable|string> STRLESS <variable|string>)` True if the given string or variable’s value is lexicographically less than the string or variable on the right.
`if(<variable|string> STRGREATER <variable|string>)` True if the given string or variable’s value is lexicographically greater than the string or variable on the right.
`if(<variable|string> STREQUAL <variable|string>)` True if the given string or variable’s value is lexicographically equal to the string or variable on the right.
`if(<variable|string> STRLESS_EQUAL <variable|string>)` True if the given string or variable’s value is lexicographically less than or equal to the string or variable on the right.
`if(<variable|string> STRGREATER_EQUAL <variable|string>)` True if the given string or variable’s value is lexicographically greater than or equal to the string or variable on the right.
`if(<variable|string> VERSION_LESS <variable|string>)` Component-wise integer version number comparison (version format is `major[.minor[.patch[.tweak]]]`).
`if(<variable|string> VERSION_GREATER <variable|string>)` Component-wise integer version number comparison (version format is `major[.minor[.patch[.tweak]]]`).
`if(<variable|string> VERSION_EQUAL <variable|string>)` Component-wise integer version number comparison (version format is `major[.minor[.patch[.tweak]]]`).
`if(<variable|string> VERSION_LESS_EQUAL <variable|string>)` Component-wise integer version number comparison (version format is `major[.minor[.patch[.tweak]]]`).
`if(<variable|string> VERSION_GREATER_EQUAL <variable|string>)` Component-wise integer version number comparison (version format is `major[.minor[.patch[.tweak]]]`).
`if(<variable|string> IN_LIST <variable>)` True if the given element is contained in the named list variable.
`if(DEFINED <variable>)` True if the given variable is defined. It does not matter if the variable is true or false just if it has been set. (Note macro arguments are not variables.)
`if((expression) AND (expression OR (expression)))` The expressions inside the parenthesis are evaluated first and then the remaining expression is evaluated as in the previous examples. Where there are nested parenthesis the innermost are evaluated as part of evaluating the expression that contains them. The if command was written very early in CMake’s history, predating the `${}` variable evaluation syntax, and for convenience evaluates variables named by its arguments as shown in the above signatures. Note that normal variable evaluation with `${}` applies before the if command even receives the arguments. Therefore code like:
```
set(var1 OFF)
set(var2 "var1")
if(${var2})
```
appears to the if command as:
```
if(var1)
```
and is evaluated according to the `if(<variable>)` case documented above. The result is `OFF` which is false. However, if we remove the `${}` from the example then the command sees:
```
if(var2)
```
which is true because `var2` is defined to “var1” which is not a false constant.
Automatic evaluation applies in the other cases whenever the above-documented signature accepts `<variable|string>`:
* The left hand argument to `MATCHES` is first checked to see if it is a defined variable, if so the variable’s value is used, otherwise the original value is used.
* If the left hand argument to `MATCHES` is missing it returns false without error
* Both left and right hand arguments to `LESS`, `GREATER`, `EQUAL`, `LESS_EQUAL`, and `GREATER_EQUAL`, are independently tested to see if they are defined variables, if so their defined values are used otherwise the original value is used.
* Both left and right hand arguments to `STRLESS`, `STRGREATER`, `STREQUAL`, `STRLESS_EQUAL`, and `STRGREATER_EQUAL` are independently tested to see if they are defined variables, if so their defined values are used otherwise the original value is used.
* Both left and right hand arguments to `VERSION_LESS`, `VERSION_GREATER`, `VERSION_EQUAL`, `VERSION_LESS_EQUAL`, and `VERSION_GREATER_EQUAL` are independently tested to see if they are defined variables, if so their defined values are used otherwise the original value is used.
* The right hand argument to `NOT` is tested to see if it is a boolean constant, if so the value is used, otherwise it is assumed to be a variable and it is dereferenced.
* The left and right hand arguments to `AND` and `OR` are independently tested to see if they are boolean constants, if so they are used as such, otherwise they are assumed to be variables and are dereferenced.
To prevent ambiguity, potential variable or keyword names can be specified in a [Quoted Argument](../manual/cmake-language.7#quoted-argument) or a [Bracket Argument](../manual/cmake-language.7#bracket-argument). A quoted or bracketed variable or keyword will be interpreted as a string and not dereferenced or interpreted. See policy [`CMP0054`](../policy/cmp0054#policy:CMP0054 "CMP0054").
| programming_docs |
cmake qt_wrap_cpp qt\_wrap\_cpp
=============
Create Qt Wrappers.
```
qt_wrap_cpp(resultingLibraryName DestName
SourceLists ...)
```
Produce moc files for all the .h files listed in the SourceLists. The moc files will be added to the library using the `DestName` source list.
cmake function function
========
Start recording a function for later invocation as a command:
```
function(<name> [arg1 [arg2 [arg3 ...]]])
COMMAND1(ARGS ...)
COMMAND2(ARGS ...)
...
endfunction(<name>)
```
Define a function named `<name>` that takes arguments named `arg1`, `arg2`, `arg3`, (…). Commands listed after function, but before the matching [`endfunction()`](endfunction#command:endfunction "endfunction"), are not invoked until the function is invoked. When it is invoked, the commands recorded in the function are first modified by replacing formal parameters (`${arg1}`) with the arguments passed, and then invoked as normal commands. In addition to referencing the formal parameters you can reference the `ARGC` variable which will be set to the number of arguments passed into the function as well as `ARGV0`, `ARGV1`, `ARGV2`, … which will have the actual values of the arguments passed in. This facilitates creating functions with optional arguments. Additionally `ARGV` holds the list of all arguments given to the function and `ARGN` holds the list of arguments past the last expected argument. Referencing to `ARGV#` arguments beyond `ARGC` have undefined behavior. Checking that `ARGC` is greater than `#` is the only way to ensure that `ARGV#` was passed to the function as an extra argument.
A function opens a new scope: see [`set(var PARENT_SCOPE)`](set#command:set "set") for details.
See the [`cmake_policy()`](cmake_policy#command:cmake_policy "cmake_policy") command documentation for the behavior of policies inside functions.
cmake add_dependencies add\_dependencies
=================
Add a dependency between top-level targets.
```
add_dependencies(<target> [<target-dependency>]...)
```
Make a top-level `<target>` depend on other top-level targets to ensure that they build before `<target>` does. A top-level target is one created by one of the [`add_executable()`](add_executable#command:add_executable "add_executable"), [`add_library()`](add_library#command:add_library "add_library"), or [`add_custom_target()`](add_custom_target#command:add_custom_target "add_custom_target") commands (but not targets generated by CMake like `install`).
Dependencies added to an [imported target](../manual/cmake-buildsystem.7#imported-targets) or an [interface library](../manual/cmake-buildsystem.7#interface-libraries) are followed transitively in its place since the target itself does not build.
See the `DEPENDS` option of [`add_custom_target()`](add_custom_target#command:add_custom_target "add_custom_target") and [`add_custom_command()`](add_custom_command#command:add_custom_command "add_custom_command") commands for adding file-level dependencies in custom rules. See the [`OBJECT_DEPENDS`](../prop_sf/object_depends#prop_sf:OBJECT_DEPENDS "OBJECT_DEPENDS") source file property to add file-level dependencies to object files.
cmake install_programs install\_programs
=================
Deprecated. Use the [`install(PROGRAMS)`](install#command:install "install") command instead.
This command has been superceded by the [`install()`](install#command:install "install") command. It is provided for compatibility with older CMake code. The `FILES` form is directly replaced by the `PROGRAMS` form of the [`install()`](install#command:install "install") command. The regexp form can be expressed more clearly using the `GLOB` form of the [`file()`](file#command:file "file") command.
```
install_programs(<dir> file1 file2 [file3 ...])
install_programs(<dir> FILES file1 [file2 ...])
```
Create rules to install the listed programs into the given directory. Use the `FILES` argument to guarantee that the file list version of the command will be used even when there is only one argument.
```
install_programs(<dir> regexp)
```
In the second form any program in the current source directory that matches the regular expression will be installed.
This command is intended to install programs that are not built by cmake, such as shell scripts. See the `TARGETS` form of the [`install()`](install#command:install "install") command to create installation rules for targets built by cmake.
The directory `<dir>` is relative to the installation prefix, which is stored in the variable [`CMAKE_INSTALL_PREFIX`](../variable/cmake_install_prefix#variable:CMAKE_INSTALL_PREFIX "CMAKE_INSTALL_PREFIX").
cmake exec_program exec\_program
=============
Deprecated. Use the [`execute_process()`](execute_process#command:execute_process "execute_process") command instead.
Run an executable program during the processing of the CMakeList.txt file.
```
exec_program(Executable [directory in which to run]
[ARGS <arguments to executable>]
[OUTPUT_VARIABLE <var>]
[RETURN_VALUE <var>])
```
The executable is run in the optionally specified directory. The executable can include arguments if it is double quoted, but it is better to use the optional `ARGS` argument to specify arguments to the program. This is because cmake will then be able to escape spaces in the executable path. An optional argument `OUTPUT_VARIABLE` specifies a variable in which to store the output. To capture the return value of the execution, provide a `RETURN_VALUE`. If `OUTPUT_VARIABLE` is specified, then no output will go to the stdout/stderr of the console running cmake.
cmake qt_wrap_ui qt\_wrap\_ui
============
Create Qt user interfaces Wrappers.
```
qt_wrap_ui(resultingLibraryName HeadersDestName
SourcesDestName SourceLists ...)
```
Produce .h and .cxx files for all the .ui files listed in the `SourceLists`. The .h files will be added to the library using the `HeadersDestNamesource` list. The .cxx files will be added to the library using the `SourcesDestNamesource` list.
cmake foreach foreach
=======
Evaluate a group of commands for each value in a list.
```
foreach(loop_var arg1 arg2 ...)
COMMAND1(ARGS ...)
COMMAND2(ARGS ...)
...
endforeach(loop_var)
```
All commands between foreach and the matching endforeach are recorded without being invoked. Once the endforeach is evaluated, the recorded list of commands is invoked once for each argument listed in the original foreach command. Before each iteration of the loop `${loop_var}` will be set as a variable with the current value in the list.
```
foreach(loop_var RANGE total)
foreach(loop_var RANGE start stop [step])
```
Foreach can also iterate over a generated range of numbers. There are three types of this iteration:
* When specifying single number, the range will have elements 0 to “total”.
* When specifying two numbers, the range will have elements from the first number to the second number.
* The third optional number is the increment used to iterate from the first number to the second number.
```
foreach(loop_var IN [LISTS [list1 [...]]]
[ITEMS [item1 [...]]])
```
Iterates over a precise list of items. The `LISTS` option names list-valued variables to be traversed, including empty elements (an empty string is a zero-length list). (Note macro arguments are not variables.) The `ITEMS` option ends argument parsing and includes all arguments following it in the iteration.
cmake configure_file configure\_file
===============
Copy a file to another location and modify its contents.
```
configure_file(<input> <output>
[COPYONLY] [ESCAPE_QUOTES] [@ONLY]
[NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])
```
Copies an `<input>` file to an `<output>` file and substitutes variable values referenced as `@VAR@` or `${VAR}` in the input file content. Each variable reference will be replaced with the current value of the variable, or the empty string if the variable is not defined. Furthermore, input lines of the form:
```
#cmakedefine VAR ...
```
will be replaced with either:
```
#define VAR ...
```
or:
```
/* #undef VAR */
```
depending on whether `VAR` is set in CMake to any value not considered a false constant by the [`if()`](if#command:if "if") command. The “…” content on the line after the variable name, if any, is processed as above. Input file lines of the form `#cmakedefine01 VAR` will be replaced with either `#define VAR 1` or `#define VAR 0` similarly.
If the input file is modified the build system will re-run CMake to re-configure the file and generate the build system again.
The arguments are:
`<input>` Path to the input file. A relative path is treated with respect to the value of [`CMAKE_CURRENT_SOURCE_DIR`](../variable/cmake_current_source_dir#variable:CMAKE_CURRENT_SOURCE_DIR "CMAKE_CURRENT_SOURCE_DIR"). The input path must be a file, not a directory.
`<output>` Path to the output file or directory. A relative path is treated with respect to the value of [`CMAKE_CURRENT_BINARY_DIR`](../variable/cmake_current_binary_dir#variable:CMAKE_CURRENT_BINARY_DIR "CMAKE_CURRENT_BINARY_DIR"). If the path names an existing directory the output file is placed in that directory with the same file name as the input file.
`COPYONLY` Copy the file without replacing any variable references or other content. This option may not be used with `NEWLINE_STYLE`.
`ESCAPE_QUOTES` Escape any substituted quotes with backslashes (C-style).
`@ONLY` Restrict variable replacement to references of the form `@VAR@`. This is useful for configuring scripts that use `${VAR}` syntax.
`NEWLINE_STYLE <style>` Specify the newline style for the output file. Specify `UNIX` or `LF` for `\n` newlines, or specify `DOS`, `WIN32`, or `CRLF` for `\r\n` newlines. This option may not be used with `COPYONLY`. Example
-------
Consider a source tree containing a `foo.h.in` file:
```
#cmakedefine FOO_ENABLE
#cmakedefine FOO_STRING "@FOO_STRING@"
```
An adjacent `CMakeLists.txt` may use `configure_file` to configure the header:
```
option(FOO_ENABLE "Enable Foo" ON)
if(FOO_ENABLE)
set(FOO_STRING "foo")
endif()
configure_file(foo.h.in foo.h @ONLY)
```
This creates a `foo.h` in the build directory corresponding to this source directory. If the `FOO_ENABLE` option is on, the configured file will contain:
```
#define FOO_ENABLE
#define FOO_STRING "foo"
```
Otherwise it will contain:
```
/* #undef FOO_ENABLE */
/* #undef FOO_STRING */
```
One may then use the [`include_directories()`](include_directories#command:include_directories "include_directories") command to specify the output directory as an include directory:
```
include_directories(${CMAKE_CURRENT_BINARY_DIR})
```
so that sources may include the header as `#include <foo.h>`.
cmake CPACK_START_MENU_SHORTCUTS CPACK\_START\_MENU\_SHORTCUTS
=============================
Species a list of shortcut names that should be created in the Start Menu for this file.
The property is currently only supported by the WIX generator.
cmake CPACK_STARTUP_SHORTCUTS CPACK\_STARTUP\_SHORTCUTS
=========================
Species a list of shortcut names that should be created in the Startup folder for this file.
The property is currently only supported by the WIX generator.
cmake CPACK_NEVER_OVERWRITE CPACK\_NEVER\_OVERWRITE
=======================
Request that this file not be overwritten on install or reinstall.
The property is currently only supported by the WIX generator.
cmake CPACK_PERMANENT CPACK\_PERMANENT
================
Request that this file not be removed on uninstall.
The property is currently only supported by the WIX generator.
cmake CPACK_DESKTOP_SHORTCUTS CPACK\_DESKTOP\_SHORTCUTS
=========================
Species a list of shortcut names that should be created on the Desktop for this file.
The property is currently only supported by the WIX generator.
cmake CPACK_WIX_ACL CPACK\_WIX\_ACL
===============
Specifies access permissions for files or directories installed by a WiX installer.
The property can contain multiple list entries, each of which has to match the following format.
```
<user>[@<domain>]=<permission>[,<permission>]
```
`<user>` and `<domain>` specify the windows user and domain for which the `<Permission>` element should be generated.
`<permission>` is any of the YesNoType attributes listed here:
```
http://wixtoolset.org/documentation/manual/v3/xsd/wix/permission.html
```
cmake TYPE TYPE
====
Widget type for entry in GUIs.
Cache entry values are always strings, but CMake GUIs present widgets to help users set values. The GUIs use this property as a hint to determine the widget type. Valid TYPE values are:
```
BOOL = Boolean ON/OFF value.
PATH = Path to a directory.
FILEPATH = Path to a file.
STRING = Generic string value.
INTERNAL = Do not present in GUI at all.
STATIC = Value managed by CMake, do not change.
UNINITIALIZED = Type not yet specified.
```
Generally the TYPE of a cache entry should be set by the command which creates it (set, option, find\_library, etc.).
cmake STRINGS STRINGS
=======
Enumerate possible STRING entry values for GUI selection.
For cache entries with type STRING, this enumerates a set of values. CMake GUIs may use this to provide a selection widget instead of a generic string entry field. This is for convenience only. CMake does not enforce that the value matches one of those listed.
cmake HELPSTRING HELPSTRING
==========
Help associated with entry in GUIs.
This string summarizes the purpose of an entry to help users set it through a CMake GUI.
cmake ADVANCED ADVANCED
========
True if entry should be hidden by default in GUIs.
This is a boolean value indicating whether the entry is considered interesting only for advanced configuration. The mark\_as\_advanced() command modifies this property.
cmake VALUE VALUE
=====
Value of a cache entry.
This property maps to the actual value of a cache entry. Setting this property always sets the value without checking, so use with care.
cmake MODIFIED MODIFIED
========
Internal management property. Do not set or get.
This is an internal cache entry property managed by CMake to track interactive user modification of entries. Ignore it.
cmake CMP0009 CMP0009
=======
FILE GLOB\_RECURSE calls should not follow symlinks by default.
In CMake 2.6.1 and below, FILE GLOB\_RECURSE calls would follow through symlinks, sometimes coming up with unexpectedly large result sets because of symlinks to top level directories that contain hundreds of thousands of files.
This policy determines whether or not to follow symlinks encountered during a FILE GLOB\_RECURSE call. The OLD behavior for this policy is to follow the symlinks. The NEW behavior for this policy is not to follow the symlinks by default, but only if FOLLOW\_SYMLINKS is given as an additional argument to the FILE command.
This policy was introduced in CMake version 2.6.2. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0048 CMP0048
=======
The [`project()`](../command/project#command:project "project") command manages VERSION variables.
CMake version 3.0 introduced the `VERSION` option of the [`project()`](../command/project#command:project "project") command to specify a project version as well as the name. In order to keep [`PROJECT_VERSION`](../variable/project_version#variable:PROJECT_VERSION "PROJECT_VERSION") and related variables consistent with variable [`PROJECT_NAME`](../variable/project_name#variable:PROJECT_NAME "PROJECT_NAME") it is necessary to set the VERSION variables to the empty string when no `VERSION` is given to [`project()`](../command/project#command:project "project"). However, this can change behavior for existing projects that set VERSION variables themselves since [`project()`](../command/project#command:project "project") may now clear them. This policy controls the behavior for compatibility with such projects.
The OLD behavior for this policy is to leave VERSION variables untouched. The NEW behavior for this policy is to set VERSION as documented by the [`project()`](../command/project#command:project "project") command.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0033 CMP0033
=======
The [`export_library_dependencies()`](../command/export_library_dependencies#command:export_library_dependencies "export_library_dependencies") command should not be called.
This command was added in January 2003 to export `<tgt>_LIB_DEPENDS` internal CMake cache entries to a file for installation with a project. This was used at the time to allow transitive link dependencies to work for applications outside of the original build tree of a project. The functionality has been superseded by the [`export()`](../command/export#command:export "export") and [`install(EXPORT)`](../command/install#command:install "install") commands.
CMake >= 3.0 prefer that this command never be called. The OLD behavior for this policy is to allow the command to be called. The NEW behavior for this policy is to issue a FATAL\_ERROR when the command is called.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0064 CMP0064
=======
Recognize `TEST` as a operator for the [`if()`](../command/if#command:if "if") command.
The `TEST` operator was added to the [`if()`](../command/if#command:if "if") command to determine if a given test name was created by the [`add_test()`](../command/add_test#command:add_test "add_test") command.
The `OLD` behavior for this policy is to ignore the `TEST` operator. The `NEW` behavior is to interpret the `TEST` operator.
This policy was introduced in CMake version 3.4. CMake version 3.9.6 warns when the policy is not set and uses `OLD` behavior. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set it to `OLD` or `NEW` explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0025 CMP0025
=======
Compiler id for Apple Clang is now `AppleClang`.
CMake 3.0 and above recognize that Apple Clang is a different compiler than upstream Clang and that they have different version numbers. CMake now prefers to present this to projects by setting the [`CMAKE_<LANG>_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") variable to `AppleClang` instead of `Clang`. However, existing projects may assume the compiler id for Apple Clang is just `Clang` as it was in CMake versions prior to 3.0. Therefore this policy determines for Apple Clang which compiler id to report in the [`CMAKE_<LANG>_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") variable after language `<LANG>` is enabled by the [`project()`](../command/project#command:project "project") or [`enable_language()`](../command/enable_language#command:enable_language "enable_language") command. The policy must be set prior to the invocation of either command.
The OLD behavior for this policy is to use compiler id `Clang`. The NEW behavior for this policy is to use compiler id `AppleClang`.
This policy was introduced in CMake version 3.0. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set this policy to OLD or NEW explicitly. Unlike most policies, CMake version 3.9.6 does *not* warn by default when this policy is not set and simply uses OLD behavior. See documentation of the [`CMAKE_POLICY_WARNING_CMP0025`](# "CMAKE_POLICY_WARNING_CMP<NNNN>") variable to control the warning.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
| programming_docs |
cmake CMP0052 CMP0052
=======
Reject source and build dirs in installed INTERFACE\_INCLUDE\_DIRECTORIES.
CMake 3.0 and lower allowed subdirectories of the source directory or build directory to be in the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") of installed and exported targets, if the directory was also a subdirectory of the installation prefix. This makes the installation depend on the existence of the source dir or binary dir, and the installation will be broken if either are removed after installation.
See [Include Directories and Usage Requirements](../manual/cmake-buildsystem.7#include-directories-and-usage-requirements) for more on specifying include directories for targets.
The OLD behavior for this policy is to export the content of the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") with the source or binary directory. The NEW behavior for this policy is to issue an error if such a directory is used.
This policy was introduced in CMake version 3.1. CMake version 3.9.6 warns when the policy is not set and uses `OLD` behavior. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set it to `OLD` or `NEW` explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0005 CMP0005
=======
Preprocessor definition values are now escaped automatically.
This policy determines whether or not CMake should generate escaped preprocessor definition values added via add\_definitions. CMake versions 2.4 and below assumed that only trivial values would be given for macros in add\_definitions calls. It did not attempt to escape non-trivial values such as string literals in generated build rules. CMake versions 2.6 and above support escaping of most values, but cannot assume the user has not added escapes already in an attempt to work around limitations in earlier versions.
The OLD behavior for this policy is to place definition values given to add\_definitions directly in the generated build rules without attempting to escape anything. The NEW behavior for this policy is to generate correct escapes for all native build tools automatically. See documentation of the COMPILE\_DEFINITIONS target property for limitations of the escaping implementation.
This policy was introduced in CMake version 2.6.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0013 CMP0013
=======
Duplicate binary directories are not allowed.
CMake 2.6.3 and below silently permitted add\_subdirectory() calls to create the same binary directory multiple times. During build system generation files would be written and then overwritten in the build tree and could lead to strange behavior. CMake 2.6.4 and above explicitly detect duplicate binary directories. CMake 2.6.4 always considers this case an error. In CMake 2.8.0 and above this policy determines whether or not the case is an error. The OLD behavior for this policy is to allow duplicate binary directories. The NEW behavior for this policy is to disallow duplicate binary directories with an error.
This policy was introduced in CMake version 2.8.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0044 CMP0044
=======
Case sensitive `<LANG>_COMPILER_ID` generator expressions
CMake 2.8.12 introduced the `<LANG>_COMPILER_ID` [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") to allow comparison of the [`CMAKE_<LANG>_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") with a test value. The possible valid values are lowercase, but the comparison with the test value was performed case-insensitively.
The OLD behavior for this policy is to perform a case-insensitive comparison with the value in the `<LANG>_COMPILER_ID` expression. The NEW behavior for this policy is to perform a case-sensitive comparison with the value in the `<LANG>_COMPILER_ID` expression.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0068 CMP0068
=======
`RPATH` settings on macOS do not affect `install_name`.
CMake 3.9 and newer remove any effect the following settings may have on the `install_name` of a target on macOS:
* [`BUILD_WITH_INSTALL_RPATH`](../prop_tgt/build_with_install_rpath#prop_tgt:BUILD_WITH_INSTALL_RPATH "BUILD_WITH_INSTALL_RPATH") target property
* [`SKIP_BUILD_RPATH`](../prop_tgt/skip_build_rpath#prop_tgt:SKIP_BUILD_RPATH "SKIP_BUILD_RPATH") target property
* [`CMAKE_SKIP_RPATH`](../variable/cmake_skip_rpath#variable:CMAKE_SKIP_RPATH "CMAKE_SKIP_RPATH") variable
* [`CMAKE_SKIP_INSTALL_RPATH`](../variable/cmake_skip_install_rpath#variable:CMAKE_SKIP_INSTALL_RPATH "CMAKE_SKIP_INSTALL_RPATH") variable
Previously, setting [`BUILD_WITH_INSTALL_RPATH`](../prop_tgt/build_with_install_rpath#prop_tgt:BUILD_WITH_INSTALL_RPATH "BUILD_WITH_INSTALL_RPATH") had the effect of setting both the `install_name` of a target to [`INSTALL_NAME_DIR`](../prop_tgt/install_name_dir#prop_tgt:INSTALL_NAME_DIR "INSTALL_NAME_DIR") and the `RPATH` to [`INSTALL_RPATH`](../prop_tgt/install_rpath#prop_tgt:INSTALL_RPATH "INSTALL_RPATH"). In CMake 3.9, it only affects setting of `RPATH`. However, if one wants [`INSTALL_NAME_DIR`](../prop_tgt/install_name_dir#prop_tgt:INSTALL_NAME_DIR "INSTALL_NAME_DIR") to apply to the target in the build tree, one may set [`BUILD_WITH_INSTALL_NAME_DIR`](../prop_tgt/build_with_install_name_dir#prop_tgt:BUILD_WITH_INSTALL_NAME_DIR "BUILD_WITH_INSTALL_NAME_DIR").
If [`SKIP_BUILD_RPATH`](../prop_tgt/skip_build_rpath#prop_tgt:SKIP_BUILD_RPATH "SKIP_BUILD_RPATH"), [`CMAKE_SKIP_RPATH`](../variable/cmake_skip_rpath#variable:CMAKE_SKIP_RPATH "CMAKE_SKIP_RPATH") or [`CMAKE_SKIP_INSTALL_RPATH`](../variable/cmake_skip_install_rpath#variable:CMAKE_SKIP_INSTALL_RPATH "CMAKE_SKIP_INSTALL_RPATH") were used to strip the directory portion of the `install_name` of a target, one may set `INSTALL_NAME_DIR=""` instead.
The `OLD` behavior of this policy is to use the `RPATH` settings for `install_name` on macOS. The `NEW` behavior of this policy is to ignore the `RPATH` settings for `install_name` on macOS.
This policy was introduced in CMake version 3.9. CMake version 3.9.6 warns when the policy is not set and uses `OLD` behavior. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set it to `OLD` or `NEW` explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0029 CMP0029
=======
The [`subdir_depends()`](../command/subdir_depends#command:subdir_depends "subdir_depends") command should not be called.
The implementation of this command has been empty since December 2001 but was kept in CMake for compatibility for a long time.
CMake >= 3.0 prefer that this command never be called. The OLD behavior for this policy is to allow the command to be called. The NEW behavior for this policy is to issue a FATAL\_ERROR when the command is called.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0028 CMP0028
=======
Double colon in target name means ALIAS or IMPORTED target.
CMake 2.8.12 and lower allowed the use of targets and files with double colons in target\_link\_libraries, with some buildsystem generators.
The use of double-colons is a common pattern used to namespace IMPORTED targets and ALIAS targets. When computing the link dependencies of a target, the name of each dependency could either be a target, or a file on disk. Previously, if a target was not found with a matching name, the name was considered to refer to a file on disk. This can lead to confusing error messages if there is a typo in what should be a target name.
The OLD behavior for this policy is to search for targets, then files on disk, even if the search term contains double-colons. The NEW behavior for this policy is to issue a FATAL\_ERROR if a link dependency contains double-colons but is not an IMPORTED target or an ALIAS target.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0069 CMP0069
=======
[`INTERPROCEDURAL_OPTIMIZATION`](../prop_tgt/interprocedural_optimization#prop_tgt:INTERPROCEDURAL_OPTIMIZATION "INTERPROCEDURAL_OPTIMIZATION") is enforced when enabled.
CMake 3.9 and newer prefer to add IPO flags whenever the [`INTERPROCEDURAL_OPTIMIZATION`](../prop_tgt/interprocedural_optimization#prop_tgt:INTERPROCEDURAL_OPTIMIZATION "INTERPROCEDURAL_OPTIMIZATION") target property is enabled and produce an error if flags are not known to CMake for the current compiler. Since a given compiler may not support IPO flags in all environments in which it is used, it is now the project’s responsibility to use the [`CheckIPOSupported`](../module/checkiposupported#module:CheckIPOSupported "CheckIPOSupported") module to check for support before enabling the [`INTERPROCEDURAL_OPTIMIZATION`](../prop_tgt/interprocedural_optimization#prop_tgt:INTERPROCEDURAL_OPTIMIZATION "INTERPROCEDURAL_OPTIMIZATION") target property. This approach allows a project to conditionally activate IPO when supported. It also allows an end user to set the [`CMAKE_INTERPROCEDURAL_OPTIMIZATION`](../variable/cmake_interprocedural_optimization#variable:CMAKE_INTERPROCEDURAL_OPTIMIZATION "CMAKE_INTERPROCEDURAL_OPTIMIZATION") variable in an environment known to support IPO even if the project does not enable the property.
Since CMake 3.8 and lower only honored [`INTERPROCEDURAL_OPTIMIZATION`](../prop_tgt/interprocedural_optimization#prop_tgt:INTERPROCEDURAL_OPTIMIZATION "INTERPROCEDURAL_OPTIMIZATION") for the Intel compiler on Linux, some projects may unconditionally enable the target property. Policy `CMP0069` provides compatibility with such projects.
This policy takes effect whenever the IPO property is enabled. The `OLD` behavior for this policy is to add IPO flags only for Intel compiler on Linux. The `NEW` behavior for this policy is to add IPO flags for the current compiler or produce an error if CMake does not know the flags.
This policy was introduced in CMake version 3.9. CMake version 3.9.6 warns when the policy is not set and uses `OLD` behavior. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set it to `OLD` or `NEW` explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
Examples
--------
Behave like CMake 3.8 and do not apply any IPO flags except for Intel compiler on Linux:
```
cmake_minimum_required(VERSION 3.8)
project(foo)
# ...
set_property(TARGET ... PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
```
Use the [`CheckIPOSupported`](../module/checkiposupported#module:CheckIPOSupported "CheckIPOSupported") module to detect whether IPO is supported by the current compiler, environment, and CMake version. Produce a fatal error if support is not available:
```
cmake_minimum_required(VERSION 3.9) # CMP0069 NEW
project(foo)
include(CheckIPOSupported)
check_ipo_supported()
# ...
set_property(TARGET ... PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
```
Apply IPO flags only if compiler supports it:
```
cmake_minimum_required(VERSION 3.9) # CMP0069 NEW
project(foo)
include(CheckIPOSupported)
# ...
check_ipo_supported(RESULT result)
if(result)
set_property(TARGET ... PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
endif()
```
Apply IPO flags without any checks. This may lead to build errors if IPO is not supported by the compiler in the current environment. Produce an error if CMake does not know IPO flags for the current compiler:
```
cmake_minimum_required(VERSION 3.9) # CMP0069 NEW
project(foo)
# ...
set_property(TARGET ... PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
```
cmake CMP0045 CMP0045
=======
Error on non-existent target in get\_target\_property.
In CMake 2.8.12 and lower, the [`get_target_property()`](../command/get_target_property#command:get_target_property "get_target_property") command accepted a non-existent target argument without issuing any error or warning. The result variable is set to a `-NOTFOUND` value.
The OLD behavior for this policy is to issue no warning and set the result variable to a `-NOTFOUND` value. The NEW behavior for this policy is to issue a `FATAL_ERROR` if the command is called with a non-existent target.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0012 CMP0012
=======
if() recognizes numbers and boolean constants.
In CMake versions 2.6.4 and lower the if() command implicitly dereferenced arguments corresponding to variables, even those named like numbers or boolean constants, except for 0 and 1. Numbers and boolean constants such as true, false, yes, no, on, off, y, n, notfound, ignore (all case insensitive) were recognized in some cases but not all. For example, the code “if(TRUE)” might have evaluated as false. Numbers such as 2 were recognized only in boolean expressions like “if(NOT 2)” (leading to false) but not as a single-argument like “if(2)” (also leading to false). Later versions of CMake prefer to treat numbers and boolean constants literally, so they should not be used as variable names.
The OLD behavior for this policy is to implicitly dereference variables named like numbers and boolean constants. The NEW behavior for this policy is to recognize numbers and boolean constants without dereferencing variables with such names.
This policy was introduced in CMake version 2.8.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0004 CMP0004
=======
Libraries linked may not have leading or trailing whitespace.
CMake versions 2.4 and below silently removed leading and trailing whitespace from libraries linked with code like
```
target_link_libraries(myexe " A ")
```
This could lead to subtle errors in user projects.
The OLD behavior for this policy is to silently remove leading and trailing whitespace. The NEW behavior for this policy is to diagnose the existence of such whitespace as an error. The setting for this policy used when checking the library names is that in effect when the target is created by an add\_executable or add\_library command.
This policy was introduced in CMake version 2.6.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0053 CMP0053
=======
Simplify variable reference and escape sequence evaluation.
CMake 3.1 introduced a much faster implementation of evaluation of the [Variable References](../manual/cmake-language.7#variable-references) and [Escape Sequences](../manual/cmake-language.7#escape-sequences) documented in the [`cmake-language(7)`](../manual/cmake-language.7#manual:cmake-language(7) "cmake-language(7)") manual. While the behavior is identical to the legacy implementation in most cases, some corner cases were cleaned up to simplify the behavior. Specifically:
* Expansion of `@VAR@` reference syntax defined by the [`configure_file()`](../command/configure_file#command:configure_file "configure_file") and [`string(CONFIGURE)`](../command/string#command:string "string") commands is no longer performed in other contexts.
* Literal `${VAR}` reference syntax may contain only alphanumeric characters (`A-Z`, `a-z`, `0-9`) and the characters `_`, `.`, `/`, `-`, and `+`. Variables with other characters in their name may still be referenced indirectly, e.g.
```
set(varname "otherwise & disallowed $ characters")
message("${${varname}}")
```
* The setting of policy [`CMP0010`](cmp0010#policy:CMP0010 "CMP0010") is not considered, so improper variable reference syntax is always an error.
* More characters are allowed to be escaped in variable names. Previously, only `()#" \@^` were valid characters to escape. Now any non-alphanumeric, non-semicolon, non-NUL character may be escaped following the `escape_identity` production in the [Escape Sequences](../manual/cmake-language.7#escape-sequences) section of the [`cmake-language(7)`](../manual/cmake-language.7#manual:cmake-language(7) "cmake-language(7)") manual.
The `OLD` behavior for this policy is to honor the legacy behavior for variable references and escape sequences. The `NEW` behavior is to use the simpler variable expansion and escape sequence evaluation rules.
This policy was introduced in CMake version 3.1. CMake version 3.9.6 warns when the policy is not set and uses `OLD` behavior. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set it to `OLD` or `NEW` explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0024 CMP0024
=======
Disallow include export result.
CMake 2.8.12 and lower allowed use of the include() command with the result of the export() command. This relies on the assumption that the export() command has an immediate effect at configure-time during a cmake run. Certain properties of targets are not fully determined until later at generate-time, such as the link language and complete list of link libraries. Future refactoring will change the effect of the export() command to be executed at generate-time. Use ALIAS targets instead in cases where the goal is to refer to targets by another name.
The OLD behavior for this policy is to allow including the result of an export() command. The NEW behavior for this policy is not to allow including the result of an export() command.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
| programming_docs |
cmake CMP0065 CMP0065
=======
Do not add flags to export symbols from executables without the [`ENABLE_EXPORTS`](../prop_tgt/enable_exports#prop_tgt:ENABLE_EXPORTS "ENABLE_EXPORTS") target property.
CMake 3.3 and below, for historical reasons, always linked executables on some platforms with flags like `-rdynamic` to export symbols from the executables for use by any plugins they may load via `dlopen`. CMake 3.4 and above prefer to do this only for executables that are explicitly marked with the [`ENABLE_EXPORTS`](../prop_tgt/enable_exports#prop_tgt:ENABLE_EXPORTS "ENABLE_EXPORTS") target property.
The `OLD` behavior of this policy is to always use the additional link flags when linking executables regardless of the value of the [`ENABLE_EXPORTS`](../prop_tgt/enable_exports#prop_tgt:ENABLE_EXPORTS "ENABLE_EXPORTS") target property.
The `NEW` behavior of this policy is to only use the additional link flags when linking executables if the [`ENABLE_EXPORTS`](../prop_tgt/enable_exports#prop_tgt:ENABLE_EXPORTS "ENABLE_EXPORTS") target property is set to `True`.
This policy was introduced in CMake version 3.4. Unlike most policies, CMake version 3.9.6 does *not* warn by default when this policy is not set and simply uses OLD behavior. See documentation of the [`CMAKE_POLICY_WARNING_CMP0065`](# "CMAKE_POLICY_WARNING_CMP<NNNN>") variable to control the warning.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0032 CMP0032
=======
The [`output_required_files()`](../command/output_required_files#command:output_required_files "output_required_files") command should not be called.
This command was added in June 2001 to expose the then-current CMake implicit dependency scanner. CMake’s real implicit dependency scanner has evolved since then but is not exposed through this command. The scanning capabilities of this command are very limited and this functionality is better achieved through dedicated outside tools.
CMake >= 3.0 prefer that this command never be called. The OLD behavior for this policy is to allow the command to be called. The NEW behavior for this policy is to issue a FATAL\_ERROR when the command is called.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0049 CMP0049
=======
Do not expand variables in target source entries.
CMake 2.8.12 and lower performed and extra layer of variable expansion when evaluating source file names:
```
set(a_source foo.c)
add_executable(foo \${a_source})
```
This was undocumented behavior.
The OLD behavior for this policy is to expand such variables when processing the target sources. The NEW behavior for this policy is to issue an error if such variables need to be expanded.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0008 CMP0008
=======
Libraries linked by full-path must have a valid library file name.
In CMake 2.4 and below it is possible to write code like
```
target_link_libraries(myexe /full/path/to/somelib)
```
where “somelib” is supposed to be a valid library file name such as “libsomelib.a” or “somelib.lib”. For Makefile generators this produces an error at build time because the dependency on the full path cannot be found. For VS IDE and Xcode generators this used to work by accident because CMake would always split off the library directory and ask the linker to search for the library by name (-lsomelib or somelib.lib). Despite the failure with Makefiles, some projects have code like this and build only with VS and/or Xcode. This version of CMake prefers to pass the full path directly to the native build tool, which will fail in this case because it does not name a valid library file.
This policy determines what to do with full paths that do not appear to name a valid library file. The OLD behavior for this policy is to split the library name from the path and ask the linker to search for it. The NEW behavior for this policy is to trust the given path and pass it directly to the native build tool unchanged.
This policy was introduced in CMake version 2.6.1. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0054 CMP0054
=======
Only interpret [`if()`](../command/if#command:if "if") arguments as variables or keywords when unquoted.
CMake 3.1 and above no longer implicitly dereference variables or interpret keywords in an [`if()`](../command/if#command:if "if") command argument when it is a [Quoted Argument](../manual/cmake-language.7#quoted-argument) or a [Bracket Argument](../manual/cmake-language.7#bracket-argument).
The `OLD` behavior for this policy is to dereference variables and interpret keywords even if they are quoted or bracketed. The `NEW` behavior is to not dereference variables or interpret keywords that have been quoted or bracketed.
Given the following partial example:
```
set(A E)
set(E "")
if("${A}" STREQUAL "")
message("Result is TRUE before CMake 3.1 or when CMP0054 is OLD")
else()
message("Result is FALSE in CMake 3.1 and above if CMP0054 is NEW")
endif()
```
After explicit expansion of variables this gives:
```
if("E" STREQUAL "")
```
With the policy set to `OLD` implicit expansion reduces this semantically to:
```
if("" STREQUAL "")
```
With the policy set to `NEW` the quoted arguments will not be further dereferenced:
```
if("E" STREQUAL "")
```
This policy was introduced in CMake version 3.1. CMake version 3.9.6 warns when the policy is not set and uses `OLD` behavior. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set it to `OLD` or `NEW` explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0003 CMP0003
=======
Libraries linked via full path no longer produce linker search paths.
This policy affects how libraries whose full paths are NOT known are found at link time, but was created due to a change in how CMake deals with libraries whose full paths are known. Consider the code
```
target_link_libraries(myexe /path/to/libA.so)
```
CMake 2.4 and below implemented linking to libraries whose full paths are known by splitting them on the link line into separate components consisting of the linker search path and the library name. The example code might have produced something like
```
... -L/path/to -lA ...
```
in order to link to library A. An analysis was performed to order multiple link directories such that the linker would find library A in the desired location, but there are cases in which this does not work. CMake versions 2.6 and above use the more reliable approach of passing the full path to libraries directly to the linker in most cases. The example code now produces something like
```
... /path/to/libA.so ....
```
Unfortunately this change can break code like
```
target_link_libraries(myexe /path/to/libA.so B)
```
where “B” is meant to find “/path/to/libB.so”. This code is wrong because the user is asking the linker to find library B but has not provided a linker search path (which may be added with the link\_directories command). However, with the old linking implementation the code would work accidentally because the linker search path added for library A allowed library B to be found.
In order to support projects depending on linker search paths added by linking to libraries with known full paths, the OLD behavior for this policy will add the linker search paths even though they are not needed for their own libraries. When this policy is set to OLD, CMake will produce a link line such as
```
... -L/path/to /path/to/libA.so -lB ...
```
which will allow library B to be found as it was previously. When this policy is set to NEW, CMake will produce a link line such as
```
... /path/to/libA.so -lB ...
```
which more accurately matches what the project specified.
The setting for this policy used when generating the link line is that in effect when the target is created by an add\_executable or add\_library command. For the example described above, the code
```
cmake_policy(SET CMP0003 OLD) # or cmake_policy(VERSION 2.4)
add_executable(myexe myexe.c)
target_link_libraries(myexe /path/to/libA.so B)
```
will work and suppress the warning for this policy. It may also be updated to work with the corrected linking approach:
```
cmake_policy(SET CMP0003 NEW) # or cmake_policy(VERSION 2.6)
link_directories(/path/to) # needed to find library B
add_executable(myexe myexe.c)
target_link_libraries(myexe /path/to/libA.so B)
```
Even better, library B may be specified with a full path:
```
add_executable(myexe myexe.c)
target_link_libraries(myexe /path/to/libA.so /path/to/libB.so)
```
When all items on the link line have known paths CMake does not check this policy so it has no effect.
Note that the warning for this policy will be issued for at most one target. This avoids flooding users with messages for every target when setting the policy once will probably fix all targets.
This policy was introduced in CMake version 2.6.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0015 CMP0015
=======
link\_directories() treats paths relative to the source dir.
In CMake 2.8.0 and lower the link\_directories() command passed relative paths unchanged to the linker. In CMake 2.8.1 and above the link\_directories() command prefers to interpret relative paths with respect to CMAKE\_CURRENT\_SOURCE\_DIR, which is consistent with include\_directories() and other commands. The OLD behavior for this policy is to use relative paths verbatim in the linker command. The NEW behavior for this policy is to convert relative paths to absolute paths by appending the relative path to CMAKE\_CURRENT\_SOURCE\_DIR.
This policy was introduced in CMake version 2.8.1. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0042 CMP0042
=======
[`MACOSX_RPATH`](../prop_tgt/macosx_rpath#prop_tgt:MACOSX_RPATH "MACOSX_RPATH") is enabled by default.
CMake 2.8.12 and newer has support for using `@rpath` in a target’s install name. This was enabled by setting the target property [`MACOSX_RPATH`](../prop_tgt/macosx_rpath#prop_tgt:MACOSX_RPATH "MACOSX_RPATH"). The `@rpath` in an install name is a more flexible and powerful mechanism than `@executable_path` or `@loader_path` for locating shared libraries.
CMake 3.0 and later prefer this property to be ON by default. Projects wanting `@rpath` in a target’s install name may remove any setting of the [`INSTALL_NAME_DIR`](../prop_tgt/install_name_dir#prop_tgt:INSTALL_NAME_DIR "INSTALL_NAME_DIR") and [`CMAKE_INSTALL_NAME_DIR`](../variable/cmake_install_name_dir#variable:CMAKE_INSTALL_NAME_DIR "CMAKE_INSTALL_NAME_DIR") variables.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0039 CMP0039
=======
Utility targets may not have link dependencies.
CMake 2.8.12 and lower allowed using utility targets in the left hand side position of the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command. This is an indicator of a bug in user code.
The OLD behavior for this policy is to ignore attempts to set the link libraries of utility targets. The NEW behavior for this policy is to report an error if an attempt is made to set the link libraries of a utility target.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0058 CMP0058
=======
Ninja requires custom command byproducts to be explicit.
When an intermediate file generated during the build is consumed by an expensive operation or a large tree of dependents, one may reduce the work needed for an incremental rebuild by updating the file timestamp only when its content changes. With this approach the generation rule must have a separate output file that is always updated with a new timestamp that is newer than any dependencies of the rule so that the build tool re-runs the rule only when the input changes. We refer to the separate output file as a rule’s *witness* and the generated file as a rule’s *byproduct*.
Byproducts may not be listed as outputs because their timestamps are allowed to be older than the inputs. No build tools (like `make`) that existed when CMake was designed have a way to express byproducts. Therefore CMake versions prior to 3.2 had no way to specify them. Projects typically left byproducts undeclared in the rules that generate them. For example:
```
add_custom_command(
OUTPUT witness.txt
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_CURRENT_SOURCE_DIR}/input.txt
byproduct.txt # timestamp may not change
COMMAND ${CMAKE_COMMAND} -E touch witness.txt
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/input.txt
)
add_custom_target(Provider DEPENDS witness.txt)
add_custom_command(
OUTPUT generated.c
COMMAND expensive-task -i byproduct.txt -o generated.c
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/byproduct.txt
)
add_library(Consumer generated.c)
add_dependencies(Consumer Provider)
```
This works well for all generators except [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja"). The Ninja build tool sees a rule listing `byproduct.txt` as a dependency and no rule listing it as an output. Ninja then complains that there is no way to satisfy the dependency and stops building even though there are order-only dependencies that ensure `byproduct.txt` will exist before its consumers need it. See discussion of this problem in [Ninja Issue 760](https://github.com/martine/ninja/issues/760) for further details on why Ninja works this way.
Instead of leaving byproducts undeclared in the rules that generate them, Ninja expects byproducts to be listed along with other outputs. Such rules may be marked with a `restat` option that tells Ninja to check the timestamps of outputs after the rules run. This prevents byproducts whose timestamps do not change from causing their dependents to re-build unnecessarily.
Since the above approach does not tell CMake what custom command generates `byproduct.txt`, the Ninja generator does not have enough information to add the byproduct as an output of any rule. CMake 2.8.12 and above work around this problem and allow projects using the above approach to build by generating `phony` build rules to tell Ninja to tolerate such missing files. However, this workaround prevents Ninja from diagnosing a dependency that is really missing. It also works poorly in in-source builds where every custom command dependency, even on source files, needs to be treated this way because CMake does not have enough information to know which files are generated as byproducts of custom commands.
CMake 3.2 introduced the `BYPRODUCTS` option to the [`add_custom_command()`](../command/add_custom_command#command:add_custom_command "add_custom_command") and [`add_custom_target()`](../command/add_custom_target#command:add_custom_target "add_custom_target") commands. This option allows byproducts to be specified explicitly:
```
add_custom_command(
OUTPUT witness.txt
BYPRODUCTS byproduct.txt # explicit byproduct specification
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_CURRENT_SOURCE_DIR}/input.txt
byproduct.txt # timestamp may not change
...
```
The `BYPRODUCTS` option is used by the [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja") generator to list byproducts among the outputs of the custom commands that generate them, and is ignored by other generators.
CMake 3.3 and above prefer to require projects to specify custom command byproducts explicitly so that it can avoid using the `phony` rule workaround altogether. Policy `CMP0058` was introduced to provide compatibility with existing projects that still need the workaround.
This policy has no effect on generators other than [`Ninja`](https://cmake.org/cmake/help/v3.9/generator/Ninja.html#generator:Ninja "Ninja"). The `OLD` behavior for this policy is to generate Ninja `phony` rules for unknown dependencies in the build tree. The `NEW` behavior for this policy is to not generate these and instead require projects to specify custom command `BYPRODUCTS` explicitly.
This policy was introduced in CMake version 3.3. CMake version 3.9.6 warns when it sees unknown dependencies in out-of-source build trees if the policy is not set and then uses `OLD` behavior. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set the policy to `OLD` or `NEW` explicitly. The policy setting must be in scope at the end of the top-level `CMakeLists.txt` file of the project and has global effect.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0019 CMP0019
=======
Do not re-expand variables in include and link information.
CMake 2.8.10 and lower re-evaluated values given to the include\_directories, link\_directories, and link\_libraries commands to expand any leftover variable references at the end of the configuration step. This was for strict compatibility with VERY early CMake versions because all variable references are now normally evaluated during CMake language processing. CMake 2.8.11 and higher prefer to skip the extra evaluation.
The OLD behavior for this policy is to re-evaluate the values for strict compatibility. The NEW behavior for this policy is to leave the values untouched.
This policy was introduced in CMake version 2.8.11. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
| programming_docs |
cmake CMP0035 CMP0035
=======
The [`variable_requires()`](../command/variable_requires#command:variable_requires "variable_requires") command should not be called.
This command was introduced in November 2001 to perform some conditional logic. It has long been replaced by the [`if()`](../command/if#command:if "if") command.
CMake >= 3.0 prefer that this command never be called. The OLD behavior for this policy is to allow the command to be called. The NEW behavior for this policy is to issue a FATAL\_ERROR when the command is called.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0062 CMP0062
=======
Disallow install() of export() result.
The [`export()`](../command/export#command:export "export") command generates a file containing [Imported Targets](../manual/cmake-buildsystem.7#imported-targets), which is suitable for use from the build directory. It is not suitable for installation because it contains absolute paths to buildsystem locations, and is particular to a single build configuration.
The [`install(EXPORT)`](../command/install#command:install "install") generates and installs files which contain [Imported Targets](../manual/cmake-buildsystem.7#imported-targets). These files are generated with relative paths (unless the user specifies absolute paths), and are designed for multi-configuration use. See [Creating Packages](../manual/cmake-packages.7#creating-packages) for more.
CMake 3.3 no longer allows the use of the [`install(FILES)`](../command/install#command:install "install") command with the result of the [`export()`](../command/export#command:export "export") command.
The `OLD` behavior for this policy is to allow installing the result of an [`export()`](../command/export#command:export "export") command. The `NEW` behavior for this policy is not to allow installing the result of an [`export()`](../command/export#command:export "export") command.
This policy was introduced in CMake version 3.3. CMake version 3.9.6 warns when the policy is not set and uses `OLD` behavior. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set it to `OLD` or `NEW` explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0023 CMP0023
=======
Plain and keyword target\_link\_libraries signatures cannot be mixed.
CMake 2.8.12 introduced the target\_link\_libraries signature using the PUBLIC, PRIVATE, and INTERFACE keywords to generalize the LINK\_PUBLIC and LINK\_PRIVATE keywords introduced in CMake 2.8.7. Use of signatures with any of these keywords sets the link interface of a target explicitly, even if empty. This produces confusing behavior when used in combination with the historical behavior of the plain target\_link\_libraries signature. For example, consider the code:
```
target_link_libraries(mylib A)
target_link_libraries(mylib PRIVATE B)
```
After the first line the link interface has not been set explicitly so CMake would use the link implementation, A, as the link interface. However, the second line sets the link interface to empty. In order to avoid this subtle behavior CMake now prefers to disallow mixing the plain and keyword signatures of target\_link\_libraries for a single target.
The OLD behavior for this policy is to allow keyword and plain target\_link\_libraries signatures to be mixed. The NEW behavior for this policy is to not to allow mixing of the keyword and plain signatures.
This policy was introduced in CMake version 2.8.12. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0022 CMP0022
=======
INTERFACE\_LINK\_LIBRARIES defines the link interface.
CMake 2.8.11 constructed the ‘link interface’ of a target from properties matching `(IMPORTED_)?LINK_INTERFACE_LIBRARIES(_<CONFIG>)?`. The modern way to specify config-sensitive content is to use generator expressions and the `IMPORTED_` prefix makes uniform processing of the link interface with generator expressions impossible. The INTERFACE\_LINK\_LIBRARIES target property was introduced as a replacement in CMake 2.8.12. This new property is named consistently with the INTERFACE\_COMPILE\_DEFINITIONS, INTERFACE\_INCLUDE\_DIRECTORIES and INTERFACE\_COMPILE\_OPTIONS properties. For in-build targets, CMake will use the INTERFACE\_LINK\_LIBRARIES property as the source of the link interface only if policy CMP0022 is NEW. When exporting a target which has this policy set to NEW, only the INTERFACE\_LINK\_LIBRARIES property will be processed and generated for the IMPORTED target by default. A new option to the install(EXPORT) and export commands allows export of the old-style properties for compatibility with downstream users of CMake versions older than 2.8.12. The target\_link\_libraries command will no longer populate the properties matching LINK\_INTERFACE\_LIBRARIES(\_<CONFIG>)? if this policy is NEW.
Warning-free future-compatible code which works with CMake 2.8.7 onwards can be written by using the `LINK_PRIVATE` and `LINK_PUBLIC` keywords of [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries").
The OLD behavior for this policy is to ignore the INTERFACE\_LINK\_LIBRARIES property for in-build targets. The NEW behavior for this policy is to use the INTERFACE\_LINK\_LIBRARIES property for in-build targets, and ignore the old properties matching `(IMPORTED_)?LINK_INTERFACE_LIBRARIES(_<CONFIG>)?`.
This policy was introduced in CMake version 2.8.12. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0063 CMP0063
=======
Honor visibility properties for all target types.
The [`<LANG>_VISIBILITY_PRESET`](# "<LANG>_VISIBILITY_PRESET") and [`VISIBILITY_INLINES_HIDDEN`](../prop_tgt/visibility_inlines_hidden#prop_tgt:VISIBILITY_INLINES_HIDDEN "VISIBILITY_INLINES_HIDDEN") target properties affect visibility of symbols during dynamic linking. When first introduced these properties affected compilation of sources only in shared libraries, module libraries, and executables with the [`ENABLE_EXPORTS`](../prop_tgt/enable_exports#prop_tgt:ENABLE_EXPORTS "ENABLE_EXPORTS") property set. This was sufficient for the basic use cases of shared libraries and executables with plugins. However, some sources may be compiled as part of static libraries or object libraries and then linked into a shared library later. CMake 3.3 and above prefer to honor these properties for sources compiled in all target types. This policy preserves compatibility for projects expecting the properties to work only for some target types.
The `OLD` behavior for this policy is to ignore the visibility properties for static libraries, object libraries, and executables without exports. The `NEW` behavior for this policy is to honor the visibility properties for all target types.
This policy was introduced in CMake version 3.3. CMake version 3.9.6 warns when the policy is not set and uses `OLD` behavior. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set it to `OLD` or `NEW` explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0034 CMP0034
=======
The [`utility_source()`](../command/utility_source#command:utility_source "utility_source") command should not be called.
This command was introduced in March 2001 to help build executables used to generate other files. This approach has long been replaced by [`add_executable()`](../command/add_executable#command:add_executable "add_executable") combined with [`add_custom_command()`](../command/add_custom_command#command:add_custom_command "add_custom_command").
CMake >= 3.0 prefer that this command never be called. The OLD behavior for this policy is to allow the command to be called. The NEW behavior for this policy is to issue a FATAL\_ERROR when the command is called.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0018 CMP0018
=======
Ignore CMAKE\_SHARED\_LIBRARY\_<Lang>\_FLAGS variable.
CMake 2.8.8 and lower compiled sources in SHARED and MODULE libraries using the value of the undocumented CMAKE\_SHARED\_LIBRARY\_<Lang>\_FLAGS platform variable. The variable contained platform-specific flags needed to compile objects for shared libraries. Typically it included a flag such as -fPIC for position independent code but also included other flags needed on certain platforms. CMake 2.8.9 and higher prefer instead to use the POSITION\_INDEPENDENT\_CODE target property to determine what targets should be position independent, and new undocumented platform variables to select flags while ignoring CMAKE\_SHARED\_LIBRARY\_<Lang>\_FLAGS completely.
The default for either approach produces identical compilation flags, but if a project modifies CMAKE\_SHARED\_LIBRARY\_<Lang>\_FLAGS from its original value this policy determines which approach to use.
The OLD behavior for this policy is to ignore the POSITION\_INDEPENDENT\_CODE property for all targets and use the modified value of CMAKE\_SHARED\_LIBRARY\_<Lang>\_FLAGS for SHARED and MODULE libraries.
The NEW behavior for this policy is to ignore CMAKE\_SHARED\_LIBRARY\_<Lang>\_FLAGS whether it is modified or not and honor the POSITION\_INDEPENDENT\_CODE target property.
This policy was introduced in CMake version 2.8.9. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0059 CMP0059
=======
Do not treat `DEFINITIONS` as a built-in directory property.
CMake 3.3 and above no longer make a list of definitions available through the [`DEFINITIONS`](../prop_dir/definitions#prop_dir:DEFINITIONS "DEFINITIONS") directory property. The [`COMPILE_DEFINITIONS`](../prop_dir/compile_definitions#prop_dir:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") directory property may be used instead.
The `OLD` behavior for this policy is to provide the list of flags given so far to the [`add_definitions()`](../command/add_definitions#command:add_definitions "add_definitions") command. The `NEW` behavior is to behave as a normal user-defined directory property.
This policy was introduced in CMake version 3.3. CMake version 3.9.6 warns when the policy is not set and uses `OLD` behavior. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set it to `OLD` or `NEW` explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0038 CMP0038
=======
Targets may not link directly to themselves.
CMake 2.8.12 and lower allowed a build target to link to itself directly with a [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") call. This is an indicator of a bug in user code.
The OLD behavior for this policy is to ignore targets which list themselves in their own link implementation. The NEW behavior for this policy is to report an error if a target attempts to link to itself.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0043 CMP0043
=======
Ignore COMPILE\_DEFINITIONS\_<Config> properties
CMake 2.8.12 and lower allowed setting the [`COMPILE_DEFINITIONS_<CONFIG>`](# "COMPILE_DEFINITIONS_<CONFIG>") target property and [`COMPILE_DEFINITIONS_<CONFIG>`](# "COMPILE_DEFINITIONS_<CONFIG>") directory property to apply configuration-specific compile definitions.
Since CMake 2.8.10, the [`COMPILE_DEFINITIONS`](../prop_tgt/compile_definitions#prop_tgt:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") property has supported [`generator expressions`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") for setting configuration-dependent content. The continued existence of the suffixed variables is redundant, and causes a maintenance burden. Population of the [`COMPILE_DEFINITIONS_DEBUG`](# "COMPILE_DEFINITIONS_<CONFIG>") property may be replaced with a population of [`COMPILE_DEFINITIONS`](../prop_tgt/compile_definitions#prop_tgt:COMPILE_DEFINITIONS "COMPILE_DEFINITIONS") directly or via [`target_compile_definitions()`](../command/target_compile_definitions#command:target_compile_definitions "target_compile_definitions"):
```
# Old Interfaces:
set_property(TARGET tgt APPEND PROPERTY
COMPILE_DEFINITIONS_DEBUG DEBUG_MODE
)
set_property(DIRECTORY APPEND PROPERTY
COMPILE_DEFINITIONS_DEBUG DIR_DEBUG_MODE
)
# New Interfaces:
set_property(TARGET tgt APPEND PROPERTY
COMPILE_DEFINITIONS $<$<CONFIG:Debug>:DEBUG_MODE>
)
target_compile_definitions(tgt PRIVATE $<$<CONFIG:Debug>:DEBUG_MODE>)
set_property(DIRECTORY APPEND PROPERTY
COMPILE_DEFINITIONS $<$<CONFIG:Debug>:DIR_DEBUG_MODE>
)
```
The OLD behavior for this policy is to consume the content of the suffixed [`COMPILE_DEFINITIONS_<CONFIG>`](# "COMPILE_DEFINITIONS_<CONFIG>") target property when generating the compilation command. The NEW behavior for this policy is to ignore the content of the [`COMPILE_DEFINITIONS_<CONFIG>`](# "COMPILE_DEFINITIONS_<CONFIG>") target property .
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0014 CMP0014
=======
Input directories must have CMakeLists.txt.
CMake versions before 2.8 silently ignored missing CMakeLists.txt files in directories referenced by add\_subdirectory() or subdirs(), treating them as if present but empty. In CMake 2.8.0 and above this policy determines whether or not the case is an error. The OLD behavior for this policy is to silently ignore the problem. The NEW behavior for this policy is to report an error.
This policy was introduced in CMake version 2.8.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0002 CMP0002
=======
Logical target names must be globally unique.
Targets names created with add\_executable, add\_library, or add\_custom\_target are logical build target names. Logical target names must be globally unique because:
```
- Unique names may be referenced unambiguously both in CMake
code and on make tool command lines.
- Logical names are used by Xcode and VS IDE generators
to produce meaningful project names for the targets.
```
The logical name of executable and library targets does not have to correspond to the physical file names built. Consider using the OUTPUT\_NAME target property to create two targets with the same physical name while keeping logical names distinct. Custom targets must simply have globally unique names (unless one uses the global property ALLOW\_DUPLICATE\_CUSTOM\_TARGETS with a Makefiles generator).
This policy was introduced in CMake version 2.6.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0055 CMP0055
=======
Strict checking for the [`break()`](../command/break#command:break "break") command.
CMake 3.1 and lower allowed calls to the [`break()`](../command/break#command:break "break") command outside of a loop context and also ignored any given arguments. This was undefined behavior.
The OLD behavior for this policy is to allow [`break()`](../command/break#command:break "break") to be placed outside of loop contexts and ignores any arguments. The NEW behavior for this policy is to issue an error if a misplaced break or any arguments are found.
This policy was introduced in CMake version 3.2. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0040 CMP0040
=======
The target in the `TARGET` signature of [`add_custom_command()`](../command/add_custom_command#command:add_custom_command "add_custom_command") must exist and must be defined in current directory.
CMake 2.8.12 and lower silently ignored a custom command created with the `TARGET` signature of [`add_custom_command()`](../command/add_custom_command#command:add_custom_command "add_custom_command") if the target is unknown or was defined outside the current directory.
The `OLD` behavior for this policy is to ignore custom commands for unknown targets. The `NEW` behavior for this policy is to report an error if the target referenced in [`add_custom_command()`](../command/add_custom_command#command:add_custom_command "add_custom_command") is unknown or was defined outside the current directory.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses `OLD` behavior. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set it to `OLD` or `NEW` explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
| programming_docs |
cmake CMP0017 CMP0017
=======
Prefer files from the CMake module directory when including from there.
Starting with CMake 2.8.4, if a cmake-module shipped with CMake (i.e. located in the CMake module directory) calls include() or find\_package(), the files located in the CMake module directory are preferred over the files in CMAKE\_MODULE\_PATH. This makes sure that the modules belonging to CMake always get those files included which they expect, and against which they were developed and tested. In all other cases, the files found in CMAKE\_MODULE\_PATH still take precedence over the ones in the CMake module directory. The OLD behavior is to always prefer files from CMAKE\_MODULE\_PATH over files from the CMake modules directory.
This policy was introduced in CMake version 2.8.4. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0001 CMP0001
=======
CMAKE\_BACKWARDS\_COMPATIBILITY should no longer be used.
The OLD behavior is to check CMAKE\_BACKWARDS\_COMPATIBILITY and present it to the user. The NEW behavior is to ignore CMAKE\_BACKWARDS\_COMPATIBILITY completely.
In CMake 2.4 and below the variable CMAKE\_BACKWARDS\_COMPATIBILITY was used to request compatibility with earlier versions of CMake. In CMake 2.6 and above all compatibility issues are handled by policies and the cmake\_policy command. However, CMake must still check CMAKE\_BACKWARDS\_COMPATIBILITY for projects written for CMake 2.4 and below.
This policy was introduced in CMake version 2.6.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0056 CMP0056
=======
Honor link flags in [`try_compile()`](../command/try_compile#command:try_compile "try_compile") source-file signature.
The [`try_compile()`](../command/try_compile#command:try_compile "try_compile") command source-file signature generates a `CMakeLists.txt` file to build the source file into an executable. In order to compile the source the same way as it might be compiled by the calling project, the generated project sets the value of the [`CMAKE_<LANG>_FLAGS`](# "CMAKE_<LANG>_FLAGS") variable to that in the calling project. The value of the [`CMAKE_EXE_LINKER_FLAGS`](../variable/cmake_exe_linker_flags#variable:CMAKE_EXE_LINKER_FLAGS "CMAKE_EXE_LINKER_FLAGS") variable may be needed in some cases too, but CMake 3.1 and lower did not set it in the generated project. CMake 3.2 and above prefer to set it so that linker flags are honored as well as compiler flags. This policy provides compatibility with the pre-3.2 behavior.
The OLD behavior for this policy is to not set the value of the [`CMAKE_EXE_LINKER_FLAGS`](../variable/cmake_exe_linker_flags#variable:CMAKE_EXE_LINKER_FLAGS "CMAKE_EXE_LINKER_FLAGS") variable in the generated test project. The NEW behavior for this policy is to set the value of the [`CMAKE_EXE_LINKER_FLAGS`](../variable/cmake_exe_linker_flags#variable:CMAKE_EXE_LINKER_FLAGS "CMAKE_EXE_LINKER_FLAGS") variable in the test project to the same as it is in the calling project.
If the project code does not set the policy explicitly, users may set it on the command line by defining the [`CMAKE_POLICY_DEFAULT_CMP0056`](# "CMAKE_POLICY_DEFAULT_CMP<NNNN>") variable in the cache.
This policy was introduced in CMake version 3.2. Unlike most policies, CMake version 3.9.6 does *not* warn by default when this policy is not set and simply uses OLD behavior. See documentation of the [`CMAKE_POLICY_WARNING_CMP0056`](# "CMAKE_POLICY_WARNING_CMP<NNNN>") variable to control the warning.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0021 CMP0021
=======
Fatal error on relative paths in INCLUDE\_DIRECTORIES target property.
CMake 2.8.10.2 and lower allowed the INCLUDE\_DIRECTORIES target property to contain relative paths. The base path for such relative entries is not well defined. CMake 2.8.12 issues a FATAL\_ERROR if the INCLUDE\_DIRECTORIES property contains a relative path.
The OLD behavior for this policy is not to warn about relative paths in the INCLUDE\_DIRECTORIES target property. The NEW behavior for this policy is to issue a FATAL\_ERROR if INCLUDE\_DIRECTORIES contains a relative path.
This policy was introduced in CMake version 2.8.12. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0060 CMP0060
=======
Link libraries by full path even in implicit directories.
Policy [`CMP0003`](cmp0003#policy:CMP0003 "CMP0003") was introduced with the intention of always linking library files by full path when a full path is given to the [`target_link_libraries()`](../command/target_link_libraries#command:target_link_libraries "target_link_libraries") command. However, on some platforms (e.g. HP-UX) the compiler front-end adds alternative library search paths for the current architecture (e.g. `/usr/lib/<arch>` has alternatives to libraries in `/usr/lib` for the current architecture). On such platforms the [`find_library()`](../command/find_library#command:find_library "find_library") may find a library such as `/usr/lib/libfoo.so` that does not belong to the current architecture.
Prior to policy [`CMP0003`](cmp0003#policy:CMP0003 "CMP0003") projects would still build in such cases because the incorrect library path would be converted to `-lfoo` on the link line and the linker would find the proper library in the arch-specific search path provided by the compiler front-end implicitly. At the time we chose to remain compatible with such projects by always converting library files found in implicit link directories to `-lfoo` flags to ask the linker to search for them. This approach allowed existing projects to continue to build while still linking to libraries outside implicit link directories via full path (such as those in the build tree).
CMake does allow projects to override this behavior by using an [IMPORTED library target](../manual/cmake-buildsystem.7#imported-targets) with its [`IMPORTED_LOCATION`](../prop_tgt/imported_location#prop_tgt:IMPORTED_LOCATION "IMPORTED_LOCATION") property set to the desired full path to a library file. In fact, many [Find Modules](../manual/cmake-developer.7#find-modules) are learning to provide [Imported Targets](../manual/cmake-buildsystem.7#imported-targets) instead of just the traditional `Foo_LIBRARIES` variable listing library files. However, this makes the link line generated for a library found by a Find Module depend on whether it is linked through an imported target or not, which is inconsistent. Furthermore, this behavior has been a source of confusion because the generated link line for a library file depends on its location. It is also problematic for projects trying to link statically because flags like `-Wl,-Bstatic -lfoo -Wl,-Bdynamic` may be used to help the linker select `libfoo.a` instead of `libfoo.so` but then leak dynamic linking to following libraries. (See the [`LINK_SEARCH_END_STATIC`](../prop_tgt/link_search_end_static#prop_tgt:LINK_SEARCH_END_STATIC "LINK_SEARCH_END_STATIC") target property for a solution typically used for that problem.)
When the special case for libraries in implicit link directories was first introduced the list of implicit link directories was simply hard-coded (e.g. `/lib`, `/usr/lib`, and a few others). Since that time, CMake has learned to detect the implicit link directories used by the compiler front-end. If necessary, the [`find_library()`](../command/find_library#command:find_library "find_library") command could be taught to use this information to help find libraries of the proper architecture.
For these reasons, CMake 3.3 and above prefer to drop the special case and link libraries by full path even when they are in implicit link directories. Policy `CMP0060` provides compatibility for existing projects.
The OLD behavior for this policy is to ask the linker to search for libraries whose full paths are known to be in implicit link directories. The NEW behavior for this policy is to link libraries by full path even if they are in implicit link directories.
This policy was introduced in CMake version 3.3. Unlike most policies, CMake version 3.9.6 does *not* warn by default when this policy is not set and simply uses OLD behavior. See documentation of the [`CMAKE_POLICY_WARNING_CMP0060`](# "CMAKE_POLICY_WARNING_CMP<NNNN>") variable to control the warning.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0037 CMP0037
=======
Target names should not be reserved and should match a validity pattern.
CMake 2.8.12 and lower allowed creating targets using [`add_library()`](../command/add_library#command:add_library "add_library"), [`add_executable()`](../command/add_executable#command:add_executable "add_executable") and [`add_custom_target()`](../command/add_custom_target#command:add_custom_target "add_custom_target") with unrestricted choice for the target name. Newer cmake features such as [`cmake-generator-expressions(7)`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") and some diagnostics expect target names to match a restricted pattern.
Target names may contain upper and lower case letters, numbers, the underscore character (\_), dot(.), plus(+) and minus(-). As a special case, ALIAS targets and IMPORTED targets may contain two consequtive colons.
Target names reserved by one or more CMake generators are not allowed. Among others these include “all”, “help” and “test”.
The OLD behavior for this policy is to allow creating targets with reserved names or which do not match the validity pattern. The NEW behavior for this policy is to report an error if an add\_\* command is used with an invalid target name.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0036 CMP0036
=======
The [`build_name()`](../command/build_name#command:build_name "build_name") command should not be called.
This command was added in May 2001 to compute a name for the current operating system and compiler combination. The command has long been documented as discouraged and replaced by the [`CMAKE_SYSTEM`](../variable/cmake_system#variable:CMAKE_SYSTEM "CMAKE_SYSTEM") and [`CMAKE_<LANG>_COMPILER`](# "CMAKE_<LANG>_COMPILER") variables.
CMake >= 3.0 prefer that this command never be called. The OLD behavior for this policy is to allow the command to be called. The NEW behavior for this policy is to issue a FATAL\_ERROR when the command is called.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0061 CMP0061
=======
CTest does not by default tell `make` to ignore errors (`-i`).
The [`ctest_build()`](../command/ctest_build#command:ctest_build "ctest_build") and [`build_command()`](../command/build_command#command:build_command "build_command") commands no longer generate build commands for [Makefile Generators](../manual/cmake-generators.7#makefile-generators) with the `-i` option. Previously this was done to help build as much of tested projects as possible. However, this behavior is not consistent with other generators and also causes the return code of the `make` tool to be meaningless.
Of course users may still add this option manually by setting [`CTEST_BUILD_COMMAND`](../variable/ctest_build_command#variable:CTEST_BUILD_COMMAND "CTEST_BUILD_COMMAND") or the `MAKECOMMAND` cache entry. See the [CTest Build Step](../manual/ctest.1#ctest-build-step) `MakeCommand` setting documentation for their effects.
The `OLD` behavior for this policy is to add `-i` to `make` calls in CTest. The `NEW` behavior for this policy is to not add `-i`.
This policy was introduced in CMake version 3.3. Unlike most policies, CMake version 3.9.6 does *not* warn when this policy is not set and simply uses OLD behavior.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0020 CMP0020
=======
Automatically link Qt executables to qtmain target on Windows.
CMake 2.8.10 and lower required users of Qt to always specify a link dependency to the qtmain.lib static library manually on Windows. CMake 2.8.11 gained the ability to evaluate generator expressions while determining the link dependencies from IMPORTED targets. This allows CMake itself to automatically link executables which link to Qt to the qtmain.lib library when using IMPORTED Qt targets. For applications already linking to qtmain.lib, this should have little impact. For applications which supply their own alternative WinMain implementation and for applications which use the QAxServer library, this automatic linking will need to be disabled as per the documentation.
The OLD behavior for this policy is not to link executables to qtmain.lib automatically when they link to the QtCore IMPORTED target. The NEW behavior for this policy is to link executables to qtmain.lib automatically when they link to QtCore IMPORTED target.
This policy was introduced in CMake version 2.8.11. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0057 CMP0057
=======
Support new [`if()`](../command/if#command:if "if") IN\_LIST operator.
CMake 3.3 adds support for the new IN\_LIST operator.
The `OLD` behavior for this policy is to ignore the IN\_LIST operator. The `NEW` behavior is to interpret the IN\_LIST operator.
This policy was introduced in CMake version 3.3. CMake version 3.9.6 warns when the policy is not set and uses `OLD` behavior. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set it to `OLD` or `NEW` explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0000 CMP0000
=======
A minimum required CMake version must be specified.
CMake requires that projects specify the version of CMake to which they have been written. This policy has been put in place so users trying to build the project may be told when they need to update their CMake. Specifying a version also helps the project build with CMake versions newer than that specified. Use the cmake\_minimum\_required command at the top of your main CMakeLists.txt file:
```
cmake_minimum_required(VERSION <major>.<minor>)
```
where “<major>.<minor>” is the version of CMake you want to support (such as “2.6”). The command will ensure that at least the given version of CMake is running and help newer versions be compatible with the project. See documentation of cmake\_minimum\_required for details.
Note that the command invocation must appear in the CMakeLists.txt file itself; a call in an included file is not sufficient. However, the cmake\_policy command may be called to set policy CMP0000 to OLD or NEW behavior explicitly. The OLD behavior is to silently ignore the missing invocation. The NEW behavior is to issue an error instead of a warning. An included file may set CMP0000 explicitly to affect how this policy is enforced for the main CMakeLists.txt file.
This policy was introduced in CMake version 2.6.0.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0016 CMP0016
=======
target\_link\_libraries() reports error if its only argument is not a target.
In CMake 2.8.2 and lower the target\_link\_libraries() command silently ignored if it was called with only one argument, and this argument wasn’t a valid target. In CMake 2.8.3 and above it reports an error in this case.
This policy was introduced in CMake version 2.8.3. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0041 CMP0041
=======
Error on relative include with generator expression.
Diagnostics in CMake 2.8.12 and lower silently ignored an entry in the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") of a target if it contained a generator expression at any position.
The path entries in that target property should not be relative. High-level API should ensure that by adding either a source directory or a install directory prefix, as appropriate.
As an additional diagnostic, the [`INTERFACE_INCLUDE_DIRECTORIES`](../prop_tgt/interface_include_directories#prop_tgt:INTERFACE_INCLUDE_DIRECTORIES "INTERFACE_INCLUDE_DIRECTORIES") generated on an [`IMPORTED`](../prop_tgt/imported#prop_tgt:IMPORTED "IMPORTED") target for the install location should not contain paths in the source directory or the build directory.
The OLD behavior for this policy is to ignore relative path entries if they contain a generator expression. The NEW behavior for this policy is to report an error if a generator expression appears in another location and the path is relative.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0027 CMP0027
=======
Conditionally linked imported targets with missing include directories.
CMake 2.8.11 introduced introduced the concept of INTERFACE\_INCLUDE\_DIRECTORIES, and a check at cmake time that the entries in the INTERFACE\_INCLUDE\_DIRECTORIES of an IMPORTED target actually exist. CMake 2.8.11 also introduced generator expression support in the target\_link\_libraries command. However, if an imported target is linked as a result of a generator expression evaluation, the entries in the INTERFACE\_INCLUDE\_DIRECTORIES of that target were not checked for existence as they should be.
The OLD behavior of this policy is to report a warning if an entry in the INTERFACE\_INCLUDE\_DIRECTORIES of a generator-expression conditionally linked IMPORTED target does not exist.
The NEW behavior of this policy is to report an error if an entry in the INTERFACE\_INCLUDE\_DIRECTORIES of a generator-expression conditionally linked IMPORTED target does not exist.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
| programming_docs |
cmake CMP0066 CMP0066
=======
Honor per-config flags in [`try_compile()`](../command/try_compile#command:try_compile "try_compile") source-file signature.
The source file signature of the [`try_compile()`](../command/try_compile#command:try_compile "try_compile") command uses the value of the [`CMAKE_<LANG>_FLAGS`](# "CMAKE_<LANG>_FLAGS") variable in the test project so that the test compilation works as it would in the main project. However, CMake 3.6 and below do not also honor config-specific compiler flags such as those in the [`CMAKE_<LANG>_FLAGS_DEBUG`](# "CMAKE_<LANG>_FLAGS_DEBUG") variable. CMake 3.7 and above prefer to honor config-specific compiler flags too. This policy provides compatibility for projects that do not expect config-specific compiler flags to be used.
The `OLD` behavior of this policy is to ignore config-specific flag variables like [`CMAKE_<LANG>_FLAGS_DEBUG`](# "CMAKE_<LANG>_FLAGS_DEBUG") and only use CMake’s built-in defaults for the current compiler and platform.
The `NEW` behavior of this policy is to honor config-specific flag variabldes like [`CMAKE_<LANG>_FLAGS_DEBUG`](# "CMAKE_<LANG>_FLAGS_DEBUG").
This policy was introduced in CMake version 3.7. Unlike most policies, CMake version 3.9.6 does *not* warn by default when this policy is not set and simply uses OLD behavior. See documentation of the [`CMAKE_POLICY_WARNING_CMP0066`](# "CMAKE_POLICY_WARNING_CMP<NNNN>") variable to control the warning.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0031 CMP0031
=======
The [`load_command()`](../command/load_command#command:load_command "load_command") command should not be called.
This command was added in August 2002 to allow projects to add arbitrary commands implemented in C or C++. However, it does not work when the toolchain in use does not match the ABI of the CMake process. It has been mostly superseded by the [`macro()`](../command/macro#command:macro "macro") and [`function()`](../command/function#command:function "function") commands.
CMake >= 3.0 prefer that this command never be called. The OLD behavior for this policy is to allow the command to be called. The NEW behavior for this policy is to issue a FATAL\_ERROR when the command is called.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0046 CMP0046
=======
Error on non-existent dependency in add\_dependencies.
CMake 2.8.12 and lower silently ignored non-existent dependencies listed in the [`add_dependencies()`](../command/add_dependencies#command:add_dependencies "add_dependencies") command.
The OLD behavior for this policy is to silently ignore non-existent dependencies. The NEW behavior for this policy is to report an error if non-existent dependencies are listed in the [`add_dependencies()`](../command/add_dependencies#command:add_dependencies "add_dependencies") command.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0011 CMP0011
=======
Included scripts do automatic cmake\_policy PUSH and POP.
In CMake 2.6.2 and below, CMake Policy settings in scripts loaded by the include() and find\_package() commands would affect the includer. Explicit invocations of cmake\_policy(PUSH) and cmake\_policy(POP) were required to isolate policy changes and protect the includer. While some scripts intend to affect the policies of their includer, most do not. In CMake 2.6.3 and above, include() and find\_package() by default PUSH and POP an entry on the policy stack around an included script, but provide a NO\_POLICY\_SCOPE option to disable it. This policy determines whether or not to imply NO\_POLICY\_SCOPE for compatibility. The OLD behavior for this policy is to imply NO\_POLICY\_SCOPE for include() and find\_package() commands. The NEW behavior for this policy is to allow the commands to do their default cmake\_policy PUSH and POP.
This policy was introduced in CMake version 2.6.3. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0007 CMP0007
=======
list command no longer ignores empty elements.
This policy determines whether the list command will ignore empty elements in the list. CMake 2.4 and below list commands ignored all empty elements in the list. For example, a;b;;c would have length 3 and not 4. The OLD behavior for this policy is to ignore empty list elements. The NEW behavior for this policy is to correctly count empty elements in a list.
This policy was introduced in CMake version 2.6.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0050 CMP0050
=======
Disallow add\_custom\_command SOURCE signatures.
CMake 2.8.12 and lower allowed a signature for [`add_custom_command()`](../command/add_custom_command#command:add_custom_command "add_custom_command") which specified an input to a command. This was undocumented behavior. Modern use of CMake associates custom commands with their output, rather than their input.
The OLD behavior for this policy is to allow the use of [`add_custom_command()`](../command/add_custom_command#command:add_custom_command "add_custom_command") SOURCE signatures. The NEW behavior for this policy is to issue an error if such a signature is used.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0051 CMP0051
=======
List TARGET\_OBJECTS in SOURCES target property.
CMake 3.0 and lower did not include the `TARGET_OBJECTS` [`generator expression`](../manual/cmake-generator-expressions.7#manual:cmake-generator-expressions(7) "cmake-generator-expressions(7)") when returning the [`SOURCES`](../prop_tgt/sources#prop_tgt:SOURCES "SOURCES") target property.
Configure-time CMake code is not able to handle generator expressions. If using the [`SOURCES`](../prop_tgt/sources#prop_tgt:SOURCES "SOURCES") target property at configure time, it may be necessary to first remove generator expressions using the [`string(GENEX_STRIP)`](../command/string#command:string "string") command. Generate-time CMake code such as [`file(GENERATE)`](../command/file#command:file "file") can handle the content without stripping.
The `OLD` behavior for this policy is to omit `TARGET_OBJECTS` expressions from the [`SOURCES`](../prop_tgt/sources#prop_tgt:SOURCES "SOURCES") target property. The `NEW` behavior for this policy is to include `TARGET_OBJECTS` expressions in the output.
This policy was introduced in CMake version 3.1. CMake version 3.9.6 warns when the policy is not set and uses `OLD` behavior. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set it to `OLD` or `NEW` explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0006 CMP0006
=======
Installing MACOSX\_BUNDLE targets requires a BUNDLE DESTINATION.
This policy determines whether the install(TARGETS) command must be given a BUNDLE DESTINATION when asked to install a target with the MACOSX\_BUNDLE property set. CMake 2.4 and below did not distinguish application bundles from normal executables when installing targets. CMake 2.6 provides a BUNDLE option to the install(TARGETS) command that specifies rules specific to application bundles on the Mac. Projects should use this option when installing a target with the MACOSX\_BUNDLE property set.
The OLD behavior for this policy is to fall back to the RUNTIME DESTINATION if a BUNDLE DESTINATION is not given. The NEW behavior for this policy is to produce an error if a bundle target is installed without a BUNDLE DESTINATION.
This policy was introduced in CMake version 2.6.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0010 CMP0010
=======
Bad variable reference syntax is an error.
In CMake 2.6.2 and below, incorrect variable reference syntax such as a missing close-brace (“${FOO”) was reported but did not stop processing of CMake code. This policy determines whether a bad variable reference is an error. The OLD behavior for this policy is to warn about the error, leave the string untouched, and continue. The NEW behavior for this policy is to report an error.
If [`CMP0053`](cmp0053#policy:CMP0053 "CMP0053") is set to `NEW`, this policy has no effect and is treated as always being `NEW`.
This policy was introduced in CMake version 2.6.3. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0047 CMP0047
=======
Use `QCC` compiler id for the qcc drivers on QNX.
CMake 3.0 and above recognize that the QNX qcc compiler driver is different from the GNU compiler. CMake now prefers to present this to projects by setting the [`CMAKE_<LANG>_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") variable to `QCC` instead of `GNU`. However, existing projects may assume the compiler id for QNX qcc is just `GNU` as it was in CMake versions prior to 3.0. Therefore this policy determines for QNX qcc which compiler id to report in the [`CMAKE_<LANG>_COMPILER_ID`](# "CMAKE_<LANG>_COMPILER_ID") variable after language `<LANG>` is enabled by the [`project()`](../command/project#command:project "project") or [`enable_language()`](../command/enable_language#command:enable_language "enable_language") command. The policy must be set prior to the invocation of either command.
The OLD behavior for this policy is to use the `GNU` compiler id for the qcc and QCC compiler drivers. The NEW behavior for this policy is to use the `QCC` compiler id for those drivers.
This policy was introduced in CMake version 3.0. Use the [`cmake_policy()`](../command/cmake_policy#command:cmake_policy "cmake_policy") command to set this policy to OLD or NEW explicitly. Unlike most policies, CMake version 3.9.6 does *not* warn by default when this policy is not set and simply uses OLD behavior. See documentation of the [`CMAKE_POLICY_WARNING_CMP0047`](# "CMAKE_POLICY_WARNING_CMP<NNNN>") variable to control the warning.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0030 CMP0030
=======
The [`use_mangled_mesa()`](../command/use_mangled_mesa#command:use_mangled_mesa "use_mangled_mesa") command should not be called.
This command was created in September 2001 to support VTK before modern CMake language and custom command capabilities. VTK has not used it in years.
CMake >= 3.0 prefer that this command never be called. The OLD behavior for this policy is to allow the command to be called. The NEW behavior for this policy is to issue a FATAL\_ERROR when the command is called.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0067 CMP0067
=======
Honor language standard in [`try_compile()`](../command/try_compile#command:try_compile "try_compile") source-file signature.
The [`try_compile()`](../command/try_compile#command:try_compile "try_compile") source file signature is intended to allow callers to check whether they will be able to compile a given source file with the current toolchain. In order to match compiler behavior, any language standard mode should match. However, CMake 3.7 and below did not do this. CMake 3.8 and above prefer to honor the language standard settings for `C`, `CXX` (C++), and `CUDA` using the values of the variables:
* [`CMAKE_C_STANDARD`](../variable/cmake_c_standard#variable:CMAKE_C_STANDARD "CMAKE_C_STANDARD")
* [`CMAKE_C_STANDARD_REQUIRED`](../variable/cmake_c_standard_required#variable:CMAKE_C_STANDARD_REQUIRED "CMAKE_C_STANDARD_REQUIRED")
* [`CMAKE_C_EXTENSIONS`](../variable/cmake_c_extensions#variable:CMAKE_C_EXTENSIONS "CMAKE_C_EXTENSIONS")
* [`CMAKE_CXX_STANDARD`](../variable/cmake_cxx_standard#variable:CMAKE_CXX_STANDARD "CMAKE_CXX_STANDARD")
* [`CMAKE_CXX_STANDARD_REQUIRED`](../variable/cmake_cxx_standard_required#variable:CMAKE_CXX_STANDARD_REQUIRED "CMAKE_CXX_STANDARD_REQUIRED")
* [`CMAKE_CXX_EXTENSIONS`](../variable/cmake_cxx_extensions#variable:CMAKE_CXX_EXTENSIONS "CMAKE_CXX_EXTENSIONS")
* [`CMAKE_CUDA_STANDARD`](../variable/cmake_cuda_standard#variable:CMAKE_CUDA_STANDARD "CMAKE_CUDA_STANDARD")
* [`CMAKE_CUDA_STANDARD_REQUIRED`](../variable/cmake_cuda_standard_required#variable:CMAKE_CUDA_STANDARD_REQUIRED "CMAKE_CUDA_STANDARD_REQUIRED")
* [`CMAKE_CUDA_EXTENSIONS`](../variable/cmake_cuda_extensions#variable:CMAKE_CUDA_EXTENSIONS "CMAKE_CUDA_EXTENSIONS")
This policy provides compatibility for projects that do not expect the language standard settings to be used automatically.
The `OLD` behavior of this policy is to ignore language standard setting variables when generating the `try_compile` test project. The `NEW` behavior of this policy is to honor language standard setting variables.
This policy was introduced in CMake version 3.8. Unlike most policies, CMake version 3.9.6 does *not* warn by default when this policy is not set and simply uses OLD behavior. See documentation of the [`CMAKE_POLICY_WARNING_CMP0067`](# "CMAKE_POLICY_WARNING_CMP<NNNN>") variable to control the warning.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
cmake CMP0026 CMP0026
=======
Disallow use of the LOCATION property for build targets.
CMake 2.8.12 and lower allowed reading the LOCATION target property (and configuration-specific variants) to determine the eventual location of build targets. This relies on the assumption that all necessary information is available at configure-time to determine the final location and filename of the target. However, this property is not fully determined until later at generate-time. At generate time, the $<TARGET\_FILE> generator expression can be used to determine the eventual LOCATION of a target output.
Code which reads the LOCATION target property can be ported to use the $<TARGET\_FILE> generator expression together with the file(GENERATE) subcommand to generate a file containing the target location.
The OLD behavior for this policy is to allow reading the LOCATION properties from build-targets. The NEW behavior for this policy is to not to allow reading the LOCATION properties from build-targets.
This policy was introduced in CMake version 3.0. CMake version 3.9.6 warns when the policy is not set and uses OLD behavior. Use the cmake\_policy command to set it to OLD or NEW explicitly.
Note
The `OLD` behavior of a policy is [`deprecated by definition`](../manual/cmake-policies.7#manual:cmake-policies(7) "cmake-policies(7)") and may be removed in a future version of CMake.
enzyme Enzyme Enzyme
======
Enzyme is a JavaScript Testing utility for React that makes it easier to test your React Components' output. You can also manipulate, traverse, and in some ways simulate runtime given the output.
Enzyme's API is meant to be intuitive and flexible by mimicking jQuery's API for DOM manipulation and traversal.
Upgrading from Enzyme 2.x or React < 16
=======================================
Are you here to check whether or not Enzyme is compatible with React 16? Are you currently using Enzyme 2.x? Great! Check out our [migration guide](docs/guides/migration-from-2-to-3) for help moving on to Enzyme v3 where React 16 is supported.
###
[Installation](docs/installation/index)
To get started with enzyme, you can simply install it via npm. You will need to install enzyme along with an Adapter corresponding to the version of react (or other UI Component library) you are using. For instance, if you are using enzyme with React 16, you can run:
```
npm i --save-dev enzyme enzyme-adapter-react-16
```
Each adapter may have additional peer dependencies which you will need to install as well. For instance, `enzyme-adapter-react-16` has peer dependencies on `react` and `react-dom`.
At the moment, Enzyme has adapters that provide compatibility with `React 16.x`, `React 15.x`, `React 0.14.x` and `React 0.13.x`.
The following adapters are officially provided by enzyme, and have the following compatibility with React:
| Enzyme Adapter Package | React semver compatibility |
| --- | --- |
| `enzyme-adapter-react-16` | `^16.4.0-0` |
| `enzyme-adapter-react-16.3` | `~16.3.0-0` |
| `enzyme-adapter-react-16.2` | `~16.2` |
| `enzyme-adapter-react-16.1` | `~16.0.0-0 \ | \ | ~16.1` |
| `enzyme-adapter-react-15` | `^15.5.0` |
| `enzyme-adapter-react-15.4` | `15.0.0-0 - 15.4.x` |
| `enzyme-adapter-react-14` | `^0.14.0` |
| `enzyme-adapter-react-13` | `^0.13.0` |
Finally, you need to configure enzyme to use the adapter you want it to use. To do this, you can use the top level `configure(...)` API.
```
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
```
3rd Party Adapters
==================
It is possible for the community to create additional (non-official) adapters that will make enzyme work with other libraries. If you have made one and it's not included in the list below, feel free to make a PR to this README and add a link to it! The known 3rd party adapters are:
| Adapter Package | For Library | Status |
| --- | --- | --- |
| [`enzyme-adapter-preact-pure`](https://github.com/preactjs/enzyme-adapter-preact-pure) | [`preact`](https://github.com/developit/preact) | (stable) |
| [`enzyme-adapter-inferno`](https://github.com/bbc/enzyme-adapter-inferno) | [`inferno`](https://github.com/infernojs/inferno) | (work in progress) |
Running Enzyme Tests
====================
Enzyme is unopinionated regarding which test runner or assertion library you use, and should be compatible with all major test runners and assertion libraries out there. The documentation and examples for enzyme use [mocha](https://mochajs.org/) and [chai](http://chaijs.com/), but you should be able to extrapolate to your framework of choice.
If you are interested in using enzyme with custom assertions and convenience functions for testing your React components, you can consider using:
* [`chai-enzyme`](https://github.com/producthunt/chai-enzyme) with Mocha/Chai.
* [`jasmine-enzyme`](https://github.com/FormidableLabs/enzyme-matchers/tree/master/packages/jasmine-enzyme) with Jasmine.
* [`jest-enzyme`](https://github.com/FormidableLabs/enzyme-matchers/tree/master/packages/jest-enzyme) with Jest.
* [`should-enzyme`](https://github.com/rkotze/should-enzyme) for should.js.
* [`expect-enzyme`](https://github.com/PsychoLlama/expect-enzyme) for expect.
[Using Enzyme with Mocha](docs/guides/mocha)
[Using Enzyme with Karma](docs/guides/karma)
[Using Enzyme with Browserify](docs/guides/browserify)
[Using Enzyme with SystemJS](docs/guides/systemjs)
[Using Enzyme with Webpack](docs/guides/webpack)
[Using Enzyme with JSDOM](docs/guides/jsdom)
[Using Enzyme with React Native](docs/guides/react-native)
[Using Enzyme with Jest](docs/guides/jest)
[Using Enzyme with Lab](docs/guides/lab)
[Using Enzyme with Tape and AVA](docs/guides/tape-ava)
Basic Usage
===========
[Shallow Rendering](docs/api/shallow)
--------------------------------------
```
import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import MyComponent from './MyComponent';
import Foo from './Foo';
describe('<MyComponent />', () => {
it('renders three <Foo /> components', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find(Foo)).to.have.lengthOf(3);
});
it('renders an `.icon-star`', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find('.icon-star')).to.have.lengthOf(1);
});
it('renders children when passed in', () => {
const wrapper = shallow((
<MyComponent>
<div className="unique" />
</MyComponent>
));
expect(wrapper.contains(<div className="unique" />)).to.equal(true);
});
it('simulates click events', () => {
const onButtonClick = sinon.spy();
const wrapper = shallow(<Foo onButtonClick={onButtonClick} />);
wrapper.find('button').simulate('click');
expect(onButtonClick).to.have.property('callCount', 1);
});
});
```
Read the full [API Documentation](docs/api/shallow)
[Full DOM Rendering](docs/api/mount)
-------------------------------------
```
import React from 'react';
import sinon from 'sinon';
import { expect } from 'chai';
import { mount } from 'enzyme';
import Foo from './Foo';
describe('<Foo />', () => {
it('allows us to set props', () => {
const wrapper = mount(<Foo bar="baz" />);
expect(wrapper.props().bar).to.equal('baz');
wrapper.setProps({ bar: 'foo' });
expect(wrapper.props().bar).to.equal('foo');
});
it('simulates click events', () => {
const onButtonClick = sinon.spy();
const wrapper = mount((
<Foo onButtonClick={onButtonClick} />
));
wrapper.find('button').simulate('click');
expect(onButtonClick).to.have.property('callCount', 1);
});
it('calls componentDidMount', () => {
sinon.spy(Foo.prototype, 'componentDidMount');
const wrapper = mount(<Foo />);
expect(Foo.prototype.componentDidMount).to.have.property('callCount', 1);
Foo.prototype.componentDidMount.restore();
});
});
```
Read the full [API Documentation](docs/api/mount)
[Static Rendered Markup](docs/api/render)
------------------------------------------
```
import React from 'react';
import { expect } from 'chai';
import { render } from 'enzyme';
import Foo from './Foo';
describe('<Foo />', () => {
it('renders three `.foo-bar`s', () => {
const wrapper = render(<Foo />);
expect(wrapper.find('.foo-bar')).to.have.lengthOf(3);
});
it('renders the title', () => {
const wrapper = render(<Foo title="unique" />);
expect(wrapper.text()).to.contain('unique');
});
});
```
Read the full [API Documentation](docs/api/render)
###
React Hooks support
Enzyme supports [react hooks](https://reactjs.org/docs/hooks-intro.html) with some limitations in [`.shallow()`](https://airbnb.io/enzyme/docs/api/shallow.html) due to upstream issues in React's shallow renderer:
* `useEffect()` and `useLayoutEffect()` don't get called in the React shallow renderer. [Related issue](https://github.com/facebook/react/issues/15275)
* `useCallback()` doesn't memoize callback in React shallow renderer. [Related issue](https://github.com/facebook/react/issues/15774)
####
[`ReactTestUtils.act()`](https://reactjs.org/docs/test-utils.html#act) wrap
If you're using React 16.8+ and `.mount()`, Enzyme will wrap apis including [`.simulate()`](https://airbnb.io/enzyme/docs/api/ReactWrapper/simulate.html), [`.setProps()`](https://airbnb.io/enzyme/docs/api/ReactWrapper/setProps.html), [`.setContext()`](https://airbnb.io/enzyme/docs/api/ReactWrapper/setContext.html), [`.invoke()`](https://airbnb.io/enzyme/docs/api/ReactWrapper/invoke.html) with [`ReactTestUtils.act()`](https://reactjs.org/docs/test-utils.html#act) so you don't need to manually wrap it.
A common pattern to trigger handlers with `.act()` and assert is:
```
const wrapper = mount(<SomeComponent />);
act(() => wrapper.prop('handler')());
wrapper.update();
expect(/* ... */);
```
We cannot wrap the result of `.prop()` (or `.props()`) with `.act()` in Enzyme internally since it will break the equality of the returned value. However, you could use `.invoke()` to simplify the code:
```
const wrapper = mount(<SomeComponent />);
wrapper.invoke('handler')();
expect(/* ... */);
```
###
Future
[Enzyme Future](https://enzymejs.github.io/enzyme/docs/future.html)
###
Contributing
See the [Contributors Guide](https://enzymejs.github.io/enzyme/CONTRIBUTING.html)
###
In the wild
Organizations and projects using `enzyme` can list themselves [here](inthewild.md).
###
License
[MIT](license.md)
| programming_docs |
enzyme Working with React 0.13 Working with React 0.13
=======================
If you are wanting to use enzyme with React 0.13, but don't already have React 0.13 installed, you should do so:
```
npm i [email protected] --save
```
Next, to get started with enzyme, you can simply install it with npm:
```
npm i --save-dev enzyme enzyme-adapter-react-13
```
And then you're ready to go! In your test files you can simply `require` or `import` enzyme:
ES6:
```
// setup file
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-13';
configure({ adapter: new Adapter() });
```
```
// test file
import { shallow, mount, render } from 'enzyme';
const wrapper = shallow(<Foo />);
```
ES5:
```
// setup file
var enzyme = require('enzyme');
var Adapter = require('enzyme-adapter-react-13');
enzyme.configure({ adapter: new Adapter() });
```
```
// test file
var enzyme = require('enzyme');
var wrapper = enzyme.shallow(<Foo />);
```
enzyme Installation Installation
============
enzyme should be installed using npm:
```
npm i --save-dev enzyme
```
enzyme can be used with your test runner of choice. All examples in the documentation will be provided using [mocha](https://mochajs.org/) and [BDD style chai](http://chaijs.com/api/bdd/), although neither library is a dependency of enzyme.
Working with React 16
=====================
If you are wanting to use enzyme with React 16, but don't already have React 16 and react-dom installed, you should do so:
```
npm i --save react@16 react-dom@16
```
Next, to get started with enzyme, you can simply install it with npm:
```
npm i --save-dev enzyme enzyme-adapter-react-16
```
And then you're ready to go! In your test files you can simply `require` or `import` enzyme:
ES6:
```
// setup file
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
```
```
// test file
import { shallow, mount, render } from 'enzyme';
const wrapper = shallow(<Foo />);
```
ES5:
```
// setup file
var enzyme = require('enzyme');
var Adapter = require('enzyme-adapter-react-16');
enzyme.configure({ adapter: new Adapter() });
```
```
// test file
var enzyme = require('enzyme');
var wrapper = enzyme.shallow(<Foo />);
```
Working with React 15
=====================
If you are wanting to use Enzyme with React 15, but don't already have React 15 and react-dom installed, you should do so:
```
npm i --save react@15 react-dom@15
```
Further, enzyme requires the test utilities addon be installed:
```
npm i --save-dev react-test-renderer@15
```
Next, to get started with enzyme, you can simply install it with npm:
```
npm i --save-dev enzyme enzyme-adapter-react-15
```
And then you're ready to go! In your test files you can simply `require` or `import` enzyme:
ES6:
```
// setup file
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';
configure({ adapter: new Adapter() });
```
```
// test file
import { shallow, mount, render } from 'enzyme';
const wrapper = shallow(<Foo />);
```
ES5:
```
// setup file
var enzyme = require('enzyme');
var Adapter = require('enzyme-adapter-react-15');
enzyme.configure({ adapter: new Adapter() });
```
```
// test file
var enzyme = require('enzyme');
var wrapper = enzyme.shallow(<Foo />);
```
Working with React 0.14
=======================
If you are wanting to use Enzyme with React 0.14, but don't already have React 0.14 and react-dom installed, you should do so:
```
npm i --save [email protected] [email protected]
```
Further, enzyme with React 0.14 requires the test utilities addon be installed:
```
npm i --save-dev [email protected]
```
Next, to get started with enzyme, you can simply install it with npm:
```
npm i --save-dev enzyme enzyme-adapter-react-14
```
And then you're ready to go! In your test files you can simply `require` or `import` enzyme:
ES6:
```
// setup file
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-14';
configure({ adapter: new Adapter() });
```
```
// test file
import { shallow, mount, render } from 'enzyme';
const wrapper = shallow(<Foo />);
```
ES5:
```
// setup file
var enzyme = require('enzyme');
var Adapter = require('enzyme-adapter-react-14');
enzyme.configure({ adapter: new Adapter() });
```
```
// test file
var enzyme = require('enzyme');
var wrapper = enzyme.shallow(<Foo />);
```
Working with React 0.13
=======================
If you are wanting to use enzyme with React 0.13, but don't already have React 0.13 installed, you should do so:
```
npm i [email protected] --save
```
Next, to get started with enzyme, you can simply install it with npm:
```
npm i --save-dev enzyme enzyme-adapter-react-13
```
And then you're ready to go! In your test files you can simply `require` or `import` enzyme:
ES6:
```
// setup file
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-13';
configure({ adapter: new Adapter() });
```
```
// test file
import { shallow, mount, render } from 'enzyme';
const wrapper = shallow(<Foo />);
```
ES5:
```
// setup file
var enzyme = require('enzyme');
var Adapter = require('enzyme-adapter-react-13');
enzyme.configure({ adapter: new Adapter() });
```
```
// test file
var enzyme = require('enzyme');
var wrapper = enzyme.shallow(<Foo />);
```
enzyme Working with React 15 Working with React 15
=====================
If you are wanting to use Enzyme with React 15, but don't already have React 15 and react-dom installed, you should do so:
```
npm i --save react@15 react-dom@15
```
Further, enzyme requires the test utilities addon be installed:
```
npm i --save-dev react-test-renderer@15
```
Next, to get started with enzyme, you can simply install it with npm:
```
npm i --save-dev enzyme enzyme-adapter-react-15
```
And then you're ready to go! In your test files you can simply `require` or `import` enzyme:
ES6:
```
// setup file
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';
configure({ adapter: new Adapter() });
```
```
// test file
import { shallow, mount, render } from 'enzyme';
const wrapper = shallow(<Foo />);
```
ES5:
```
// setup file
var enzyme = require('enzyme');
var Adapter = require('enzyme-adapter-react-15');
enzyme.configure({ adapter: new Adapter() });
```
```
// test file
var enzyme = require('enzyme');
var wrapper = enzyme.shallow(<Foo />);
```
enzyme Working with React 0.14 Working with React 0.14
=======================
If you are wanting to use Enzyme with React 0.14, but don't already have React 0.14 and react-dom installed, you should do so:
```
npm i --save [email protected] [email protected]
```
Further, enzyme with React 0.14 requires the test utilities addon be installed:
```
npm i --save-dev [email protected]
```
Next, to get started with enzyme, you can simply install it with npm:
```
npm i --save-dev enzyme enzyme-adapter-react-14
```
And then you're ready to go! In your test files you can simply `require` or `import` enzyme:
ES6:
```
// setup file
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-14';
configure({ adapter: new Adapter() });
```
```
// test file
import { shallow, mount, render } from 'enzyme';
const wrapper = shallow(<Foo />);
```
ES5:
```
// setup file
var enzyme = require('enzyme');
var Adapter = require('enzyme-adapter-react-14');
enzyme.configure({ adapter: new Adapter() });
```
```
// test file
var enzyme = require('enzyme');
var wrapper = enzyme.shallow(<Foo />);
```
enzyme Working with React 16 Working with React 16
=====================
If you are wanting to use enzyme with React 16, but don't already have React 16 and react-dom installed, you should do so:
```
npm i --save react@16 react-dom@16
```
Next, to get started with enzyme, you can simply install it with npm:
```
npm i --save-dev enzyme enzyme-adapter-react-16
```
And then you're ready to go! In your test files you can simply `require` or `import` enzyme:
ES6:
```
// setup file
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
```
```
// test file
import { shallow, mount, render } from 'enzyme';
const wrapper = shallow(<Foo />);
```
ES5:
```
// setup file
var enzyme = require('enzyme');
var Adapter = require('enzyme-adapter-react-16');
enzyme.configure({ adapter: new Adapter() });
```
```
// test file
var enzyme = require('enzyme');
var wrapper = enzyme.shallow(<Foo />);
```
enzyme Using enzyme with SystemJS Using enzyme with SystemJS
==========================
If you are using a test runner that runs code in a browser-based environment, you may be using [SystemJS](systemjs) in order to bundle your React code.
Prior to enzyme 3.0 there were some issues with conditional requires that were used to maintain backwards compatibility with React versions. With enzyme 3.0+, this should no longer be an issue. If it is, please file a GitHub issue or make a PR to this documentation with instructions on how to set it up.
enzyme Using enzyme with Browserify Using enzyme with Browserify
============================
If you are using a test runner that runs code in a browser-based environment, you may be using [browserify](http://browserify.org/) in order to bundle your React code.
Prior to enzyme 3.0 there were some issues with conditional requires that were used to maintain backwards compatibility with React versions. With enzyme 3.0+, this should no longer be an issue. If it is, please file a GitHub issue or make a PR to this documentation with instructions on how to set it up.
enzyme Using enzyme to Test Components in React Native Using enzyme to Test Components in React Native
===============================================
As of v0.18, React Native uses React as a dependency rather than a forked version of the library, which means it is now possible to use enzyme's `shallow` with React Native components.
Unfortunately, React Native has many environmental dependencies that can be hard to simulate without a host device.
This can be difficult when you want your test suite to run with typical Continuous Integration servers such as Travis.
To use enzyme to test React Native, you currently need to configure an adapter, and load an emulated DOM.
Configuring an Adapter
-----------------------
While a React Native adapter is [in discussion](https://github.com/enzymejs/enzyme/issues/1436), a standard adapter may be used, such as 'enzyme-adapter-react-16':
```
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
```
Loading an emulated DOM with JSDOM
-----------------------------------
To use enzyme's `mount` until a React Native adapter exists, an emulated DOM must be loaded.
While some have had success with [react-native-mock-renderer](https://github.com/Root-App/react-native-mock-render), the recommended approach is to use [https://github.com/tmpvar/jsdom](jsdom), as documented for enzyme at the [JSDOM](https://airbnb.io/enzyme/docs/guides/jsdom.html) documentation page.
JSDOM will allow all of the `enzyme` behavior you would expect. While Jest snapshot testing can be used with this approach as well, it isn't encouraged and is only supported through `wrapper.debug()`.
Using enzyme's find when lacking className props
-------------------------------------------------
It is worth noting that React Native allows for a [testID](https://facebook.github.io/react-native/docs/view#testid) prop, that can be used a selector similar to `className` in standard React:
```
<View key={key} style={styles.todo} testID="todo-item">
<Text testID="todo-title" style={styles.title}>{todo.title}</Text>
</View>
```
```
expect(wrapper.findWhere((node) => node.prop('testID') === 'todo-item')).toExist();
```
Default example configuration for Jest and JSDOM replacement
-------------------------------------------------------------
To perform the necessary configuration in your testing framework, it is recommended to use a setup script, such as with Jest's `setupFilesAfterEnv` setting.
Create or update a `jest.config.js` file at the root of your project to include the `setupFilesAfterEnv` setting:
```
// jest.config.js
module.exports = {
// Load setup-tests.js before test execution
setupFilesAfterEnv: '<rootDir>setup-tests.js',
// ...
};
```
Then create or update the file specified in `setupFilesAfterEnv`, in this case `setup-tests.js` in the project root:
```
// setup-tests.js
import 'react-native';
import 'jest-enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Enzyme from 'enzyme';
/**
* Set up DOM in node.js environment for Enzyme to mount to
*/
const { JSDOM } = require('jsdom');
const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;
function copyProps(src, target) {
Object.defineProperties(target, {
...Object.getOwnPropertyDescriptors(src),
...Object.getOwnPropertyDescriptors(target),
});
}
global.window = window;
global.document = window.document;
global.navigator = {
userAgent: 'node.js',
};
copyProps(window, global);
/**
* Set up Enzyme to mount to DOM, simulate events,
* and inspect the DOM in tests.
*/
Enzyme.configure({ adapter: new Adapter() });
```
Configure enzyme with other test libraries and include JSDOM on the fly
------------------------------------------------------------------------
Update the file specified in `setupFilesAfterEnv`, in this case `setup-tests.js` in the project root:
```
import 'react-native';
import 'jest-enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Enzyme from 'enzyme';
/**
* Set up Enzyme to mount to DOM, simulate events,
* and inspect the DOM in tests.
*/
Enzyme.configure({ adapter: new Adapter() });
```
###
Create a separate test file
Create a file prefixed with enzyme.test.ts for example `component.enzyme.test.js`:
```
/**
* @jest-environment jsdom
*/
import React from 'react';
import { mount } from 'enzyme';
import { Text } from '../../../component/text';
describe('Component tested with airbnb enzyme', () => {
test('App mount with enzyme', () => {
const wrapper = mount(<Text />);
// other tests operations
});
});
```
**The most important part is to ensure that the test runs with the `jestEnvironment` set to `jsdom`** - one way is to include a `/* @jest-environment jsdom */` comment at the top of the file.
Then you should then be able to start writing tests!
Note that you may want to perform some additional mocking around native components, or if you want to perform snapshot testing against React Native components. Notice how you may need to mock React Navigation's `KeyGenerator` in this case, to avoid random React keys that will cause snapshots to always fail.
```
import React from 'react';
import renderer from 'react-test-renderer';
import { mount, ReactWrapper } from 'enzyme';
import { Provider } from 'mobx-react';
import { Text } from 'native-base';
import { TodoItem } from './todo-item';
import { TodoList } from './todo-list';
import { todoStore } from '../../stores/todo-store';
// https://github.com/react-navigation/react-navigation/issues/2269
// React Navigation generates random React keys, which makes
// snapshot testing fail. Mock the randomness to keep from failing.
jest.mock('react-navigation/src/routers/KeyGenerator', () => ({
generateKey: jest.fn(() => 123),
}));
describe('todo-list', () => {
describe('enzyme tests', () => {
it('can add a Todo with Enzyme', () => {
const wrapper = mount(
<Provider keyLength={0} todoStore={todoStore}>
<TodoList />
</Provider>,
);
const newTodoText = 'I need to do something...';
const newTodoTextInput = wrapper.find('Input').first();
const addTodoButton = wrapper
.find('Button')
.findWhere((w) => w.text() === 'Add Todo')
.first();
newTodoTextInput.props().onChangeText(newTodoText);
// Enzyme usually allows wrapper.simulate() alternatively, but this doesn't support 'press' events.
addTodoButton.props().onPress();
// Make sure to call update if external events (e.g. Mobx state changes)
// result in updating the component props.
wrapper.update();
// You can either check for a testID prop, similar to className in React:
expect(
wrapper.findWhere((node) => node.prop('testID') === 'todo-item'),
).toExist();
// Or even just find a component itself, if you broke the JSX out into its own component:
expect(wrapper.find(TodoItem)).toExist();
// You can even do snapshot testing,
// if you pull in enzyme-to-json and configure
// it in snapshotSerializers in package.json
expect(wrapper.find(TodoList)).toMatchSnapshot();
});
});
});
```
enzyme Using enzyme with JSDOM Using enzyme with JSDOM
=======================
[JSDOM](https://github.com/tmpvar/jsdom) is a JavaScript based headless browser that can be used to create a realistic testing environment.
Since enzyme's [`mount`](../api/mount) API requires a DOM, JSDOM is required in order to use `mount` if you are not already in a browser environment (ie, a Node environment).
For the best experience with enzyme, it is recommended that you load a document into the global scope *before* requiring React for the first time. It is very important that the below script gets run *before* React's code is run.
As a result, a standalone script like the one below is generally a good approach:
`jsdom v10~`:
```
/* setup.js */
const { JSDOM } = require('jsdom');
const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;
function copyProps(src, target) {
Object.defineProperties(target, {
...Object.getOwnPropertyDescriptors(src),
...Object.getOwnPropertyDescriptors(target),
});
}
global.window = window;
global.document = window.document;
global.navigator = {
userAgent: 'node.js',
};
global.requestAnimationFrame = function (callback) {
return setTimeout(callback, 0);
};
global.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
copyProps(window, global);
```
Here is the sample of [jsdom old API](https://github.com/tmpvar/jsdom/blob/master/lib/old-api.md) as well.
`jsdom ~<v10`:
```
/* setup.js */
const { jsdom } = require('jsdom');
global.document = jsdom('');
global.window = document.defaultView;
global.navigator = {
userAgent: 'node.js',
};
function copyProps(src, target) {
const props = Object.getOwnPropertyNames(src)
.filter((prop) => typeof target[prop] === 'undefined')
.reduce((result, prop) => ({
...result,
[prop]: Object.getOwnPropertyDescriptor(src, prop),
}), {});
Object.defineProperties(target, props);
}
copyProps(document.defaultView, global);
```
`describeWithDOM` API and clearing the document after every test
-----------------------------------------------------------------
In previous versions of enzyme, there was a public `describeWithDOM` API which loaded in a new JSDOM document into the global namespace before every test, ensuring that tests were deterministic and did not have side-effects.
This approach is no longer recommended. React's source code makes several assumptions about the environment it is running in, and one of them is that the `global.document` that is found at "require time" is going to be the one and only document it ever needs to worry about. As a result, this type of "reloading" ends up causing more pain than it prevents.
It is important, however, to make sure that your tests using the global DOM APIs do not have leaky side-effects which could change the results of other tests. Until there is a better option, this is left to you to ensure.
JSDOM + Mocha
--------------
When testing with JSDOM, the `setup.js` file above needs to be run before the test suite runs. If you are using mocha, this can be done from the command line using the `--require` option:
```
mocha --require setup.js --recursive path/to/test/dir
```
Node.js Compatibility
----------------------
Jsdom requires node 4 or above. As a result, if you want to use it with `mount`, you will need to make sure node 4 or iojs is on your machine. If you are stuck using an older version of Node, you may want to try using a browser-based test runner such as [Karma](karma).
###
Switching between node versions
Some times you may need to switch between different versions of node, you can use a CLI tool called `nvm` to quickly switch between node versions.
To install `nvm`, use the curl script from <http://nvm.sh>, and then:
```
nvm install 4
```
Now your machine will be running Node 4. You can use the `nvm use` command to switch between the two environments:
```
nvm use 0.12
```
```
nvm use 4
```
| programming_docs |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.