using different i2c address display for same code

Hello all, forgive me of what should be a simple answer but my programming abilities are limited! Thanks in advance for any help.

I have a project that uses an I2C LCD. I am not able to purchase displays with the same address for each of the units I am building. So, I need to be able to determine the address of the display (in setup) before instantiating the lcd object so that it will be global.
The typical way that I have read to determine the address is to run i2cscanner, make note of the address and hard code it so it works. I want the ability to have 1 code for all units independent of the display that it may have. I currently have 2 different addresses being used for my displays.

Is there a way to create a global object and modify the address in setup before initializing it?

#include <Wire.h>
#include <LiquidCrystal_I2C.h>


LiquidCrystal_I2C lcd(0x27, 20, 4);
void setup () {
  Wire.beginTransmission(0x27);
  if (Wire.endTransmission() == 0) {
    lcdAddr = 0x27;
  }
  
  Wire.beginTransmission(0x3F);
  if (Wire.endTransmission() == 0) {
    lcdAddr = 0x3F;
  }

  lcd.init();
}

Again, thanks in advance for any suggestions.

If you use my hd44780 library it will auto locate the i2c address of your backpack automatically.
It will also auto detect the pin mappings used on the backpack. This is important as not all backpacks are wire the PCF8574 to the LCD the same way. LiquidCrystal_I2C assumes one particular mapping/wiring and is not configurable. If you happen to purchase one that uses a different wiring than LiquidCrystal_I2C assumed, it will not work.
Since hd44780 figures out this stuff during initialization, you can swap out backpacks/LCDs and your sketch will work as soon as the Arduino is reset and restarted.

The hd44780 library can be installed from the IDE library manager. (don't use the zip install)
The i/o class is hd44780_I2Cexp.
You can read more about it on the github page: GitHub - duinoWitchery/hd44780: Extensible hd44780 LCD library
or the wiki: Home · duinoWitchery/hd44780 Wiki · GitHub

Once you install the library, run the hd44780_I2Cexp included example I2CexpDiag.
That will test things to make sure the library is properly working with your backpack.
See the other examples like HelloWorld to see what header files need to be included and how to declare the lcd object.

-- bill

Thanks, I will give it a try.
D