开发者

Differences between classpath and sourcepath options of javac

I read the Sun documentation and a开发者_如何转开发 lot of posts on Stack Overflow, but I'm still confused about the differences between the Java compiler options -cp and -sourcepath.

Let say I have this directory structure:

c:\Java\project1\src (where the Java source files are)  
c:\Java\project1\bin (where the Java class files will be or already are)  

Let's also say I have a source file MainClass.java in a package com.mypackage, and that the directory structure is ok in the source folder.

I'm in the project1 directory and run:

javac -d bin -sourcepath src src/com/mypackage/MainClass.java  

or

javac -d bin -classpath src src/com/mypackage/MainClass.java  

and I obtain the same result. In verbose mode, the search path for source files is src in both cases.

It would be great if anybody could help me figure out the specifics of these options.


 -classpath classpath

Set the user class path, overriding the user class path in the CLASSPATH environment variable. If neither CLASSPATH or -classpath is specified, the user class path consists of the current directory.

If the -sourcepath option is not specified, the user class path is searched for source files as well as class files.

-sourcepath sourcepath

Specify the source code path to search for class or interface definitions. As with the user class path, source path entries are separated by semicolons (;) and can be directories, JAR archives, or ZIP archives. If packages are used, the local path name within the directory or archive must reflect the package name.

Note that classes found through the classpath are subject to automatic recompilation if their sources are found.


  • sourcepath is where is the root of your code to compile
  • classpath can contains your code but also the libraries you need


CLASSPATH tells the compiler and the class loader where to look for the .class files it needs.

Sourcepath is something I don't use so much. I believe it's optional, because usually the current directory is the sourcepath. CLASSPATH is not.


  • classpath is searched for class (.class) files
  • sourcepath is searched for source (.java) files (.a.k.a class or interface definitions)

However, if sourcepath is NOT specified, the classpath is searched for both class files AND source files.

This leads me to believe that we can almost always keep things simple by using just classpath, and by avoiding sourcepath altogether.

People who need to use both classpath and sourcepath are probably targeting strange directory contents. For example, they might have a folder that contains source files and class files, but only want to have the source files searched for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜