Makefile Conditional Variable Assignment C++

This page describes the syntax of the build file, which glues your C and C++ source files to the Android NDK.

Overview

The file resides in a subdirectory of your project's directory, and describes your sources and shared libraries to the build system. It is really a tiny GNU makefile fragment that the build system parses once or more. The file is useful for defining project-wide settings that , the build system, and your environment variables leave undefined. It can also override project-wide settings for specific modules.

The syntax of the allows you to group your sources into modules. A module is either a static library, a shared library, or a standalone executable. You can define one or more modules in each file, and you can use the same source file in multiple modules. The build system only places shared libraries into your application package. In addition, static libraries can generate shared libraries.

In addition to packaging libraries, the build system handles a variety of other details for you. For example, you don't need to list header files or explicit dependencies between generated files in your file. The NDK build system computes these relationships automatically for you. As a result, you should be able to benefit from new toolchain/platform support in future NDK releases without having to touch your file.

The syntax of this file is very close to that used in the files distributed with the full Android Open Source Project. While the build system implementation that uses them is different, their similarity is an intentional design decision aimed at making it easier for application developers to reuse source code for external libraries.

Basics

Before exploring the syntax in detail, it is useful to start by understanding the basics of what a file contains. This section uses the file in the Hello-JNI sample toward that end, explaining the role that each line in the file plays.

An file must begin by defining the variable:

LOCAL_PATH := $(call my-dir)

This variable indicates the location of the source files in the development tree. Here, the macro function , provided by the build system, returns the path of the current directory (the directory containing the file itself).

The next line declares the variable, whose value the build system provides.

include $(CLEAR_VARS)

The variable points to a special GNU Makefile that clears many variables for you, such as , , and . Note that it does not clear . This variable must retain its value because the system parses all build control files in a single GNU Make execution context where all variables are global. You must (re-)declare this variable before describing each module.

Next, the variable stores the name of the module that you wish to build. Use this variable once per module in your application.

LOCAL_MODULE := hello-jni

Each module name must be unique and not contain any spaces. The build system, when it generates the final shared-library file, automatically adds the proper prefix and suffix to the name that you assign to . For example, the example that appears above results in generation of a library called .

Note: If your module's name already starts with , the build system does not prepend an additional prefix; it takes the module name as-is, and adds the extension. So a source file originally called, for example, still produces a shared-object file called . This behavior is to support libraries that the Android platform sources generate from files; the names of all such libraries start with .

The next line enumerates the source files, with spaces delimiting multiple files:

LOCAL_SRC_FILES := hello-jni.c

The variable must contain a list of C and/or C++ source files to build into a module.

The last line helps the system tie everything together:

include $(BUILD_SHARED_LIBRARY)

The variable points to a GNU Makefile script that collects all the information you defined in variables since the most recent . This script determines what to build, and how to do it.

There are more complex examples in the samples directories, with commented files that you can look at. In addition, Sample: native-activity provides a detailed explanation of that sample's file. Finally, Variables and Macros provides further information on the variables from this section.

Variables and Macros

The build system provides many possible variables for use in the file. Many of these variables come with preassigned values. Others, you assign.

In addition to these variables, you can also define your own arbitrary ones. If you do so, keep in mind that the NDK build system reserves the following variable names:

  • Names that begin with , such as .
  • Names that begin with , , or . The build system uses these internally.
  • Lower-case names, such as . The build system uses these internally, as well.

If you need to define your own convenience variables in an file, we recommend prepending to their names.

NDK-defined include variables

This section discusses the GNU Make variables that the build system defines before parsing your file. Under certain circumstances, the NDK might parse your file several times, using a different definition for some of these variables each time.

CLEAR_VARS

This variable points to a build script that undefines nearly all variables listed in the "Developer-defined variables" section below. Use this variable to include this script before describing a new module. The syntax for using it is:

include $(CLEAR_VARS)

BUILD_SHARED_LIBRARY

This variable points to a build script that collects all the information about the module you provided in your variables, and determines how to build a target shared library from the sources you listed. Note that using this script requires that you have already assigned values to and , at a minimum (for more information about these variables, see Module-Description Variables).

The syntax for using this variable is:

include $(BUILD_SHARED_LIBRARY)

A shared-library variable causes the build system to generate a library file with a extension.

BUILD_STATIC_LIBRARY

A variant of that is used to build a static library. The build system does not copy static libraries into your project/packages, but it can use them to build shared libraries (see and , below). The syntax for using this variable is:

include $(BUILD_STATIC_LIBRARY)

A static-library variable causes the build system to generate a library with a extension.

PREBUILT_SHARED_LIBRARY

Points to a build script used to specify a prebuilt shared library. Unlike in the case of and , here the value of cannot be a source file. Instead, it must be a single path to a prebuilt shared library, such as . The syntax for using this variable is:

include $(PREBUILT_SHARED_LIBRARY)

You can also reference a prebuilt library in another module by using the variable. For more information about using prebuilts, see Using Prebuilt Libraries.

PREBUILT_STATIC_LIBRARY

The same as , but for a prebuilt static library. For more information about using prebuilts, see Using Prebuilt Libraries.

Target information variables

The build system parses once per ABI specified by the variable, which is typically defined in your file. If is , then the build system parses once per ABI the NDK supports. This section describes variables the build system defines each time it parses .

TARGET_ARCH

The CPU family the build system is targeting as it parses this file. This variable will be one of: , , , or .

TARGET_PLATFORM

The Android API level number the build system is targeting as it parses this file. For example, the Android 5.1 system images correspond to Android API level 22: . For a complete list of platform names and corresponding Android system images, see Android NDK Native APIs. The following example shows the syntax for using this variable:

ifeq ($(TARGET_PLATFORM),android-22) # ... do something ... endif

TARGET_ARCH_ABI

The ABI the build system is targeting as it parses this file. Table 1 shows the ABI setting used for each supported CPU and architecture.

Table 1. ABI settings for different CPUs and architectures.

CPU and architectureSetting
ARMv5TE
ARMv7
ARMv8 AArch64
i686
x86-64

The following example shows how to check for ARMv8 AArch64 as the target CPU-and-ABI combination:

ifeq ($(TARGET_ARCH_ABI),arm64-v8a) # ... do something ... endif

Note: The ABI is deprecated in NDK r16 and will be removed in NDK r17.

For more details about architecture ABIs and associated compatibility issues, refer to ABI Management.

New target ABIs in the future will have different values.

TARGET_ABI

A concatenation of target Android API level and ABI. It is especially useful when you want to test against a specific target system image for a real device. For example, to check for a 64-bit ARM device running on Android API level 22:

ifeq ($(TARGET_ABI),android-22-arm64-v8a) # ... do something ... endif

Module-Description Variables

The variables in this section describe your module to the build system. Each module description should follow this basic flow:

    1. Initialize or undefine the variables associated with the module, using the variable.
    2. Assign values to the variables used to describe the module.
    3. Set the NDK build system to use the appropriate build script for the module, using the variable.

LOCAL_PATH

This variable is used to give the path of the current file. You must define it at the start of your file. The following example shows how to do so:

LOCAL_PATH := $(call my-dir)

The script to which points does not clear this variable. Therefore, you only need to define it a single time, even if your file describes multiple modules.

LOCAL_MODULE

This variable stores the name of your module. It must be unique among all module names, and must not contain any spaces. You must define it before including any scripts (other than the one for ). You need not add either the prefix or the or file extension; the build system makes these modifications automatically. Throughout your and files, refer to your module by its unmodified name. For example, the following line results in the generation of a shared library module called :

LOCAL_MODULE := "foo"

If you want the generated module to have a name other than + the value of , you can use the variable to give the generated module a name of your own choosing, instead.

LOCAL_MODULE_FILENAME

This optional variable allows you to override the names that the build system uses by default for files that it generates. For example, if the name of your is , you can force the system to call the file it generates . The following example shows how to accomplish this:

LOCAL_MODULE := foo LOCAL_MODULE_FILENAME := libnewfoo

For a shared library module, this example would generate a file called .

Note: You cannot override filepath or file extension.

LOCAL_SRC_FILES

This variable contains the list of source files that the build system uses to generate the module. Only list the files that the build system actually passes to the compiler, since the build system automatically computes any associated depencies.

Note that you can use both relative (to ) and absolute file paths.

We recommend avoiding absolute file paths; relative paths make your file more portable.

Note: Always use Unix-style forward slashes (/) in build files. The build system does not handle Windows-style backslashes (\) properly.

LOCAL_CPP_EXTENSION

You can use this optional variable to indicate a file extension other than for your C++ source files. For example, the following line changes the extension to . (The setting must include the dot.)

LOCAL_CPP_EXTENSION := .cxx

From NDK r7, you can use this variable to specify multiple extensions. For instance:

LOCAL_CPP_EXTENSION := .cxx .cpp .cc

LOCAL_CPP_FEATURES

You can use this optional variable to indicate that your code relies on specific C++ features. It enables the right compiler and linker flags during the build process. For prebuilt binaries, this variable also declares which features the binary depends on, thus helping ensure the final linking works correctly. We recommend that you use this variable instead of enabling and directly in your definition.

Using this variable allows the build system to use the appropriate flags for each module. Using causes the compiler to use all specified flags for all modules, regardless of actual need.

For example, to indicate that your code uses RTTI (RunTime Type Information), write: LOCAL_CPP_FEATURES := rtti

To indicate that your code uses C++ exceptions, write:

LOCAL_CPP_FEATURES := exceptions

You can also specify multiple values for this variable. For example:

LOCAL_CPP_FEATURES := rtti features The order in which you describe the values does not matter.

LOCAL_C_INCLUDES

You can use this optional variable to specify a list of paths, relative to the NDK directory, to add to the include search path when compiling all sources (C, C++ and Assembly). For example:

LOCAL_C_INCLUDES := sources/foo

Or even:

LOCAL_C_INCLUDES := $(LOCAL_PATH)/

Define this variable before setting any corresponding inclusion flags via or .

The build system also uses paths automatically when launching native debugging with ndk-gdb.

LOCAL_CFLAGS

This optional variable sets compiler flags for the build system to pass when building C and C++ source files. The ability to do so can be useful for specifying additional macro definitions or compile options.

Try not to change the optimization/debugging level in your file. The build system can handle this setting automatically for you, using the relevant information in the file. Doing it this way allows the build system to generate useful data files used during debugging.

Note: In android-ndk-1.5_r1, the corresponding flags only applied to C source files, not C++ ones. They now match the full Android build system behavior. (You can now use to specify flags for C++ sources only.)

It is possible to specify additional include paths by writing:

LOCAL_CFLAGS += -I<path>, It is better, however, to use for this purpose, since doing so also makes it possible to use the paths available for native debugging with ndk-gdb.

LOCAL_CPPFLAGS

An optional set of compiler flags that will be passed when building C++ source files only. They will appear after the LOCAL_CFLAGS on the compiler's command-line.

Note: In android-ndk-1.5_r1, the corresponding flags applied to both C and C++ sources. This has been corrected to match the full Android build system. To specify flags for both C and C++ sources, use .

LOCAL_STATIC_LIBRARIES

This variable stores the list of static libraries modules on which the current module depends.

If the current module is a shared library or an executable, this variable will force these libraries to be linked into the resulting binary.

If the current module is a static library, this variable simply indicates that other modules depending on the current one will also depend on the listed libraries.

LOCAL_SHARED_LIBRARIES

This variable is the list of shared libraries modules on which this module depends at runtime. This information is necessary at link time, and to embed the corresponding information in the generated file.

LOCAL_WHOLE_STATIC_LIBRARIES

This variable is a variant of , and expresses that the linker should treat the associated library modules as whole archives. For more information on whole archives, see the GNU linker's documentation for the flag.

This variable is useful when there are circular dependencies among several static libraries. When you use this variable to build a shared library, it will force the build system to add all object files from your static libraries to the final binary. The same is not true, however, when generating executables.

LOCAL_LDLIBS

This variable contains the list of additional linker flags for use in building your shared library or executable. It enables you to use the prefix to pass the name of specific system libraries. For example, the following example tells the linker to generate a module that links to at load time:

LOCAL_LDLIBS := -lz

For the list of exposed system libraries against which you can link in this NDK release, see Android NDK Native APIs.

Note: If you define this variable for a static library, the build system ignores it, and prints a warning.

LOCAL_LDFLAGS

The list of other linker flags for the build system to use when building your shared library or executable. For example, the following example uses the linker on ARM/X86 GCC 4.6+, on which is the default

LOCAL_LDFLAGS += -fuse-ld=bfd

Note: If you define this variable for a static library, the build system ignores it, and ndk-build prints a warning.

LOCAL_ALLOW_UNDEFINED_SYMBOLS

By default, when the build system encounters an undefined reference encountered while trying to build a shared, it will throw an undefined symbol error. This error can help you catch catch bugs in your source code.

To disable this check, set this variable to . Note that this setting may cause the shared library to load at runtime.

Note: If you define this variable for a static library, the build system ignores it, and ndk-build prints a warning.

LOCAL_ARM_MODE

By default, the build system generates ARM target binaries in thumb mode, where each instruction is 16 bits wide and linked with the STL libraries in the directory. Defining this variable as forces the build system to generate the module's object files in 32-bit mode. The following example shows how to do this:

LOCAL_ARM_MODE := arm

You can also instruct the build system to only build specific sources in mode by appending suffix to the source filenames. For example, the following example tells the build system to always compile in ARM mode, but to build according to the value of .

LOCAL_SRC_FILES := foo.c bar.c.arm

Note: You can also force the build system to generate ARM binaries by setting in your file to . Specifying forces an ARM build because the toolchain debugger does not handle Thumb code properly.

LOCAL_ARM_NEON

This variable only matters when you are targeting the ABI. It allows the use of ARM Advanced SIMD (NEON) GCC intrinsics in your C and C++ sources, as well as NEON instructions in Assembly files.

Note that not all ARMv7-based CPUs support the NEON instruction set extensions. For this reason, you must perform runtime detection to be able to safely use this code at runtime. For more information, see NEON Support and The Library.

Alternatively, you can use the suffix to specify that the build system only compile specific source files with NEON support. In the following example, the build system compiles with thumb and neon support, with thumb support, and with support for ARM and NEON:

LOCAL_SRC_FILES = foo.c.neon bar.c zoo.c.arm.neon

If you use both suffixes, must precede .

LOCAL_DISABLE_NO_EXECUTE

Android NDK r4 added support for the "NX bit" security feature. It is enabled by default, but you can disable it by setting this variable to . We do not recommend doing so without a compelling reason.

This feature does not modify the ABI, and is only enabled on kernels targeting ARMv6+ CPU devices. Machine code with this feature enabled will run unmodified on devices running earlier CPU architectures.

For more information, see Wikipedia: NX bit and The GNU stack kickstart.

LOCAL_DISABLE_RELRO

By default, the NDK compiles code with read-only relocations and GOT protection. This variable instructs the runtime linker to mark certain regions of memory as read-only after relocation, making certain security exploits (such as GOT overwrites) more difficult. Note that these protections are only effective on Android API level 16 and higher. On lower API levels, the code will still run, but without memory protections.

This variable is turned on by default, but you can disable it by setting its value to . We do not recommend doing so without a compelling reason.

For more information, see RELRO: RELocation Read-Only and Security enhancements in RedHat Enterprise Linux (section 6).

LOCAL_DISABLE_FORMAT_STRING_CHECKS

By default, the build system compiles code with format string protection. Doing so forces a compiler error if a non-constant format string is used in a -style function.

This protection is on by default, but you can disable it by setting the value of this variable to . We do not recommend doing so without a compelling reason.

LOCAL_EXPORT_CFLAGS

This variable records a set of C/C++ compiler flags to add to the definition of any other module that uses this one via the or variables.

For example, consider the following pair of modules: and , which depends on :

include $(CLEAR_VARS) LOCAL_MODULE := foo LOCAL_SRC_FILES := foo/foo.c LOCAL_EXPORT_CFLAGS := -DFOO=1 include $(BUILD_STATIC_LIBRARY) include $(CLEAR_VARS) LOCAL_MODULE := bar LOCAL_SRC_FILES := bar.c LOCAL_CFLAGS := -DBAR=2 LOCAL_STATIC_LIBRARIES := foo include $(BUILD_SHARED_LIBRARY)

Here, the build system passes the flags and to the compiler when building . It also prepends exported flags to your your module's so you can easily override them.

In addition, the relationship among modules is transitive: If depends on , which in turn depends on , then also inherits all flags exported from .

Finally, the build system does not use exported flags when building locally (i.e., building the module whose flags it is exporting). Thus, in the example above, it does not pass to the compiler when building . To build locally, use instead.

LOCAL_EXPORT_CPPFLAGS

This variable is the same as , but for C++ flags only.

LOCAL_EXPORT_C_INCLUDES

This variable is the same as , but for C include paths. It is useful in cases where, for example, needs to include headers from module .

LOCAL_EXPORT_LDFLAGS

This variable is the same as , but for linker flags.

LOCAL_EXPORT_LDLIBS

This variable is the same as , telling the build system to pass names of specific system libraries to the compiler. Prepend to the name of each library you specify.

Note that the build system appends imported linker flags to the value of your module's variable. It does this due to the way Unix linkers work.

This variable is typically useful when module is a static library and has code that depends on a system library. You can then use to to export the dependency. For example:

include $(CLEAR_VARS) LOCAL_MODULE := foo LOCAL_SRC_FILES := foo/foo.c LOCAL_EXPORT_LDLIBS := -llog include $(BUILD_STATIC_LIBRARY) include $(CLEAR_VARS) LOCAL_MODULE := bar LOCAL_SRC_FILES := bar.c LOCAL_STATIC_LIBRARIES := foo include $(BUILD_SHARED_LIBRARY)

In this example, the build system puts at the end of the linker command when it builds . Doing so tells the linker that, because depends on , it also depends on the system logging library.

LOCAL_SHORT_COMMANDS

Set this variable to when your module has a very high number of sources and/or dependent static or shared libraries. Doing so forces the build system to use syntax for archives containing intermediate object files or linking libraries.

This feature can be useful on Windows, where the command line accepts a maximum of only of 8191 characters, which can be too small for complex projects. It also impacts the compilation of individual source files, placing nearly all compiler flags inside list files, too.

Note that any value other than will revert to the default behaviour. You can also define in your file to force this behavior for all modules in your project.

We do not recommend enabling this feature by default, since it makes the build slower.

LOCAL_THIN_ARCHIVE

Set this variable to when building static libraries. Doing so will generate a thin archive, a library file that does not contain object files, but instead just file paths to the actual objects that it would normally contain.

This is useful to reduce the size of your build output. The drawback is that such libraries cannot be moved to a different location (all paths inside them are relative).

Valid values are , or empty. A default value can be set in your file through the variable.

Note: This is ignored for non-static library modules, or prebuilt static library ones.

LOCAL_FILTER_ASM

Define this variable as a shell command that the build system will use to filter the assembly files extracted or generated from the files you specified for .

Defining this variable causes the following things to occur:

    1. The build system generates a temporary assembly file from any C or C++ source file, instead of compiling them into an object file.
    2. The build system executes the shell command in on any temporary assembly file and on any assembly file listed in , thus generating another temporary assembly file.
    3. The build system compiles these filtered assembly files into an object file.

For example:

LOCAL_SRC_FILES := foo.c bar.S LOCAL_FILTER_ASM := foo.c --1--> $OBJS_DIR/foo.S.original --2--> $OBJS_DIR/foo.S --3--> $OBJS_DIR/foo.o bar.S --2--> $OBJS_DIR/bar.S --3--> $OBJS_DIR/bar.o

"1" corresponds to the compiler, "2" to the filter, and "3" to the assembler. The filter must be a standalone shell command that takes the name of the input file as its first argument, and the name of the output file as the second one. For example:

myasmfilter $OBJS_DIR/foo.S.original $OBJS_DIR/foo.S myasmfilter bar.S $OBJS_DIR/bar.S

NDK-provided function macros

This section explains GNU Make function macros that the NDK provides. Use to evaluate them; they return textual information.

my-dir

This macro returns the path of the last included makefile, which typically is the current 's directory. is useful for defining at the start of your file. For example:

LOCAL_PATH := $(call my-dir)

Due to the way GNU Make works, what this macro really returns is the path of the last makefile that the build system included when parsing the build scripts. For this reason, you should not call after including another file.

For example, consider the following example:

LOCAL_PATH := $(call my-dir) # ... declare one module include $(LOCAL_PATH)/foo/`Android.mk` LOCAL_PATH := $(call my-dir) # ... declare another module

The problem here is that the second call to defines as instead of , because that was where its most recent include pointed.

You can avoid this problem by putting additional includes after everything else in the file. For example:

LOCAL_PATH := $(call my-dir) # ... declare one module LOCAL_PATH := $(call my-dir) # ... declare another module # extra includes at the end of the Android.mk file include $(LOCAL_PATH)/foo/Android.mk

If it is not feasible to structure the file in this way, save the value of the first call into another variable. For example:

MY_LOCAL_PATH := $(call my-dir) LOCAL_PATH := $(MY_LOCAL_PATH) # ... declare one module include $(LOCAL_PATH)/foo/`Android.mk` LOCAL_PATH := $(MY_LOCAL_PATH) # ... declare another module

all-subdir-makefiles

Returns the list of files located in all subdirectories of the current path.

You can use this function to provide deep-nested source directory hierarchies to the build system. By default, the NDK only looks for files in the directory containing the file.

this-makefile

Returns the path of the current makefile (from which the build system called the function).

parent-makefile

Returns the path of the parent makefile in the inclusion tree (the path of the makefile that included the current one).

grand-parent-makefile

Returns the path of the grandparent makefile in the inclusion tree (the path of the makefile that included the current one).

import-module

A function that allows you to find and include a module's file by the name of the module. A typical example is as follows:

$(call import-module,<name>)

In this example, the build system looks for the module tagged in the list of directories referenced that your environment variable references, and includes its file automatically for you.

Additional sample code

To download NDK samples, see NDK Samples.

You need to step back a little bit and think about what's going on here: you seem to just be throwing things into your makefile and hoping the result is what you want, rather than really understanding what's happening and proceeding with a purpose to solve your problem.

The first thing to understand is how make invokes a recipe: first, make expands the recipe. Expanding means make looks through the text of the recipe and finds anything that begins with a and treats it like a make function or variable, and evaluates it. So, is converted into a single , is expanded to the value of that variable, and is a make function which is run and the results are included in the recipe text. Maybe you can already see where your recipe is going wrong...

Then second, AFTER all of the recipe has been expanded, make takes the expanded text of the recipe and passes it to the shell. Make then waits for the shell to complete, and make looks at the exit code of the shell. If it's , then the recipe succeeds and make continues. If it's not , then the recipe fails and make exits with an error. There is NO INTERACTION between make and the shell except make starts it with a script to run, and gets back the exit code. If you couldn't before, maybe you can now see where your recipe is going wrong.

It's virtually always an error (or at least unnecessary) to use a function inside a recipe... the recipe is already running in the shell! You don't need make to run another shell first, then give those results to a new shell.

Your shell invocation is trying to use a shell variable, . But that variable has no value here, when make runs the function, because make runs that function before it starts your shell script. You can't have things in your make functions that refer to things that won't be defined until the recipe is running. This will run the shell script , but the shell variable is not set so the find will recurse through everything under .

Second, you are misusing here. The shell function expands to a list of words, say foo bar baz. Then the will look like this:

which is the same as writing just this:

which is the same as running the command with an argument , after setting the variable to the value . Which is why it seems to be "running your directory".

You probably wanted this:

(note quotes). However, getting quotes through an is tricky" you have to escape them. Luckily you don't need at all here anyway, because you're not trying to assign a dynamically named variable. You can just write the assignment directly.

So, losing the shell function and the eval, that line should be written:

Ditto for the echo: you don't need the there.

However, I really don't see the point of setting this variable or the variable either. You never do anything with them.

0 thoughts on “Makefile Conditional Variable Assignment C++

Leave a Reply

Your email address will not be published. Required fields are marked *