Java Reference
In-Depth Information
We place the source code for these two methods in a file called
NativeHel-
loWorld.cpp
in our
src/javatech/jni22
directory.
22.3.5 Compile the native implementation
Recall that we instructed
javah
to direct its output to the
build/headers
directory. Therefore we must arrange the C/C
compiler command line argu-
ments to specify our
build/headers
directory as a compiler include directory.
Unfortunately, since C is not platform portable, compiling instructions are dif-
ferent for different platforms. We begin with a Windows example, since most
readers probably have access to a Windows system.
We assume that Microsoft Visual C
++
is installed on the user's Windows
machine. There are, however, other alternatives, including the excellent and free
CYGWIN library (see [4]) which includes the GNU C
++
++
compiler as well as
many other Unix-like tools.
First, we must enable command-line usage of the C/C
++
compiler by
running the
vcvars32.bat
script. In a standard Visual C
installation,
that script appears in
C:
\
program files
\
microsoft visual studio
\
vc98
\
bin
\
vcvars32.bat
. The command line compiler tool is
cl
.
When compiling, we must specify the location of the needed include files. The
cl
tool uses
/I
<
dir
>
(or
-I
<
dir
>
)tospecify directories to add to the include
file search path. There are three such include files - the header file generated
by
javah
, the
jni.h
file that is included by the generated header file, and a
machine-dependent header file that is included by
jni.h
.
We already know that the generated header file is in the
build/headers
directory (known as
build
\
headers
, with a backslash, on Windows).
The
jni.h
file appears, on Windows, in
%JAVA
-
HOME%
\
include
where
JAVA
-
HOME
is the Java 2 SDK installation directory. The machine-dependent file
appears in
%JAVA
-
HOME%
\
include
\
win32
.Soour command line to compile
the implementation source becomes
++
cl -c -Ibuild\headers -I%JAVA
-
HOME%\include I%JAVA
-
HOME%\
include\win32 -Fobuild\objs\NativeHelloWorld.obj
src\javatech\jni22\NativeHelloWorld.cpp
We have used the
-c
switch to specify compile-only and
-Fo
<
file
>
to name
the output directory and file name of the compiled .
obj
file. Notice that we
have continued the pattern of placing compiled output in the
build
directory by
placing the .
obj
file into a
build
\
objs
directory. That way, it is easy to clean
up all generated and compiled output simply by deleting the
build
directory. For
this choice to work, we must create the
build
\
objs
directory before running
the above command. (Although the line above is shown as three lines to fit on
the page, it must be entered as all one line in a Windows command shell or batch
script.)
Search WWH ::
Custom Search