Frank Vilea
Frank Vilea

Reputation: 8487

C: Create a global variable with the return value from a function

I'm programming a simple library to return my db user and pass. This all works fine. However, I've already a finished C app, that I want to adjust without putting the new values (user and pass) into every possible function. Hence, I thought I'd simply make them global.

So before my int main() I've got

const char * mySQLUsername = getMySQLPassword();
const char * mySQLPassword = getMySQLUsername();

But because it's a function, my compiler is complaining:

error: initializer element is not constant

How do I work around this problem without having to put in extra code everywhere?

Upvotes: 0

Views: 132

Answers (1)

Mark Elliot
Mark Elliot

Reputation: 77044

Just run the functions in your initializer, say, as the first operational thing you do in main.

 //...
 const char * mySQLUsername;
 //...

 int main(int argc, char **argv){
     // variable declarations, etc.

     mySQLUsername = getMySQLUsername();

     //...

Or alternatively, put the intializers in a function:

 //...
 const char * mySQLUsername;
 //...

 void initGlobalVars(){
     mySQLUsername = getMySQLUsername();
     //...others...
 }

 int main(int argc, char **argv){
     // variable declarations
     initGlobalVars();
     //...

Upvotes: 3

Related Questions