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?
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();
//...
精彩评论