---
title: "使用Javah 生成C/C++头文件"
author: "脑壳冒星星"
date: "2014-05-06T19:56:43Z"
tags: ["JNI", "Java"]
categories: ["编程语言"]
slug: "javah-c-c"
draft: false
lastmod: "2014-05-06T20:00:35Z"
id: 2062303
url: "https://ethan-li.iteye.com/blog/2062303"
---

假设我们已经有了这个类jni_test，准备用它生成调用C语言的头文件。另外，这个Java文件是在路径“D:\workspace\PrepareForExam\scr”下，包“package com.example.myclass;”


```java
package com.example.myclass;
public class jni_test {
    private native final void init();
    private native final void init2(int a,int b);
}
```


**1、首先我们要编译一下这个类，以便得到类对应的*.class**
**2、我们要开始写javah的命令，以便生成对应的C语言头文件
**
cd D:\workspace\PrepareForExam\src
javah -classpath D:\workspace\PrepareForExam\bin -d d:/ -jni com.example.myclass.jni_test

其中java中各个命令的意思是
-classpath <路径> 用于装入类的路径
-d <目录> 输出目录
-jni 生成 JNI样式的头文件（默认）

注意到以上我们命令中指定的路径

注意到我们的命令符的执行位置是源代码目录”D:\workspace\PrepareForExam\src”

-classpath  后面的路径是指包”com.example.myclass”所在的根路径

-jni 后面的路径是包名+类名

**3、最终输出的C语言头文件**


```c++
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_example_myclass_jni_test */

#ifndef _Included_com_example_myclass_jni_test
#define _Included_com_example_myclass_jni_test
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_example_myclass_jni_test
 * Method:    init
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_com_example_myclass_jni_1test_init
  (JNIEnv *, jobject);

/*
 * Class:     com_example_myclass_jni_test
 * Method:    init2
 * Signature: (II)V
 */
JNIEXPORT void JNICALL Java_com_example_myclass_jni_1test_init2
  (JNIEnv *, jobject, jint, jint);

#ifdef __cplusplus
}
#endif
#endif
```