开发者

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

开发者 https://www.devze.com 2023-03-20 21:42 出处:网络
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

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?


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();
     //...
0

精彩评论

暂无评论...
验证码 换一张
取 消