Differences between classpath and sourcepath optio

2019-01-11 00:55发布

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.

4条回答
家丑人穷心不美
2楼-- · 2019-01-11 01:18
  • 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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-11 01:25
 -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.

查看更多
神经病院院长
4楼-- · 2019-01-11 01:25
  • sourcepath is where is the root of your code to compile
  • classpath can contains your code but also the libraries you need
查看更多
Ridiculous、
5楼-- · 2019-01-11 01:33

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.

查看更多
登录 后发表回答