- Android NDK Game Development Cookbook
- Sergey Kosarevsky Viktor Latypov
- 536字
- 2021-07-21 18:21:24
Compiling the native static libraries for Windows
To build the Windows version of libraries, we need a C++ compiler. We use MinGW with the GCC toolchain described in Chapter 1, Establishing a Build Environment. For each library, we have a collection of source-code files, and we need to get the static library, a file with the .a
extension.
Getting ready
Let us assume the src
directory contains the source code of a library we need to build for Android.
How to do it...
- Let us start with writing a makefile:
CFLAGS = -I src
This line defines a variable with a list of compiler command-line parameters. In our case, we instruct the compiler to search the
src
directory for header files. If the library source code spans across many directories, we need to add the–I
switch for each of the directories. - Next, we add the following lines for each source file:
<SourceFile>.o: gcc $(CFLAGS) –c <SourceFile>.cpp –o <SourceFile>.o
<SourceFile>
should be replaced by the actual name of the.cpp
source file, and these lines should be written for each of the source files. - Now, we add the list of object files:
ObjectFiles = <SourceFile1>.o <SourceFile2>.o ...
- Finally, we write the target for our library:
<LibraryName>: ar –rvs <LibraryName>.a $(ObjectList)
- To build the library, invoke the following command:
>make <LibraryName>.a
When using the library in our programs, we pass the
LibraryName.a
file as a parameter togcc
.
How it works...
Makefiles consist of targets similar to subroutines in programming languages, and usually each target results in an object file being generated. For example, we have seen that each source file of the library gets compiled into the corresponding object file.
Target names may include the file name pattern to avoid copying and pasting, but in the simplest case, we just list all the source files and duplicate those lines replacing SourceFile
with the appropriate file names. The –c
switch after the gcc
command is the option to compile the source file and –o
specifies the name of the output object file. The $(CFLAGS)
symbol denotes the substitution of the value of the CFLAGS
variable to the command line.
The GCC toolchain for Windows includes the AR
tool, which is an abbreviation for the archiver. Makefiles for our libraries invoke this tool to create a static version of the library. This is done in the last lines of the makefile.
There’s more...
Here are some tips for writing makefiles:
- When a line, with a list of object files becomes too long, it can be split using the backslash symbol like the following:
ObjectFileList = File1.o \ ... \ FileN.o
- Sometimes, comments are required. This can be done by writing a line, which starts with a sharp character:
# This line is a comment
If the header files for the library do not reside in the same directory as the source files, we have to add those directories to the CFLAGS
list.