Working on multiple module project. How to create global variable that can be shared with multiple modules and also global variable will be changed by any module and other module can get the changed value.
Creating a variable using
project.ext.set(“testCounter”, 5)
and in the sub module I am modifying the value
project.testCounter = (project.testCounter + testCount)
project.testCounter value is not changed.
Each subproject has its own project object, so accessing “project” in a submodule is accessing a different object. You do have access to the root project, though, so “rootProject.testCounter” is probably what you want.
I added the rootProject.testCounter = 0 in the settings.gradle then it showing below error
FAILURE: Build failed with an exception.
-
Where:
Settings file ‘C:\workspace\github\trunk\settings.gradle’ line: 6 -
What went wrong:
A problem occurred evaluating settings ‘trunk’.
No such property: testCounter for class: org.gradle.initialization.DefaultProjectDescriptor
- Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
Then I added rootProject.testCounter = 0 in root project build.gradle
FAILURE: Build failed with an exception.
-
Where:
Build file ‘C:\workspace\github\trunk\build.gradle’ line: 30 -
What went wrong:
A problem occurred evaluating root project ‘trunk’.
No such property: testCounter for class: org.gradle.api.internal.project.DefaultProject_Decorated
It’s an extension property, so it has to be declared as an extension property. So in the root project’s build.gradle you would need to do “project.ext.testCounter=0” and then in each subproject, you could reference it as rootProject.testCounter.
On a different note, global properties like this are usually a bad idea. It might make more sense to track these values at the individual project level and then just gather and add them all up when you need them using subprojects.each or something similar.
Thanks Gary…I like your approach.