How to share source code between projects?

Hi there,

I have 3 projects: shared1, shared2, app1 and app2.

Now when I build them, I get 4 individual JARs. But I want app1 and app2 (which both depend on shared1 and shared2) to work standalone.

I know that I could merge the JAR files, but seems fragile. I’d rather somehow have Gradle build app1 by using the source directories of shared1, shared2 and app1.

How do I make that work?

Regards Stephan

You’ll need to configure the source sets of the projects to also point to the extra dirs.

You’ll also need to make sure both projects have the correct dependencies.

Thanks, Luke. Lightning fast reply.

This is my directory layout:

  |--- app1
  |--- app2
      |--- shared1
      |--- shared2

I then tried to define the sourceSets:

sourceSets {
        main {
            java {
                srcDir 'src/main/java'
                srcDir '${rootProject.projectDir}/modules/shared1/src/main/java'
                srcDir '${rootProject.projectDir}/modules/shared2/src/main/java'

The problem was that when I created an IDEA project it didn’t really work, since IntelliJ was saying the source directory was “outside of the content root”.

So could I somehow just keep the regular configuration for IDEA and only when I want to publish something, bundle the source directories?

Cheers Stephan

Simplest way would be to then try and undo these changes in the IDEA model:

Thanks. I think I almost got it.

One problem now is that the generated POM of “app1” contains the dependency “shared1”, but I’d rather have it contain all dependencies of “shared1” directly (“flattened”).

I tried adding the project’s dependencies manually:

dependencies {
        compile project(":modules:shared1")
        compile project(":modules:shared1").configurations.compile

But this generates a StackOverflowError.

So how can I (recursively) add all dependencies of a project to another?

Regards Stephan

I’m not sure if this will work, but try this:

configurations {
  compile.extendsFrom project(":modules:shared1").configurations.compile

StackOverflowError again :frowning:

If you push an example project that tries to do what you want, I’ll take a look. Putting it up on GitHub would be the most convenient.

It’s under

Currently as a workaround I created a list of the dependencies (“libraries”) and added them manually. EDIT: And the source directories are also in a list (“moduleDirs”)