Reputation: 36
I have 2 header files, login.h and inmenu.h. login.h has included inmenu.h as well.
Now login.h defines an external variable extern char *password_login which is in a var.h header file as
printf("Enter the password: \n");
char *password_login = (char *)calloc(MAX, sizeof(char));
scanf("%1000s", password_login);
After that when i call inmenu() function from inmenu header file and try to access password_login value
char *tmpsqluppass = concatsqluppass(password_login, newpass);
This fails saying undefined reference to password_login
/usr/bin/ld: /tmp/ccKZpQvi.o: warning: relocation against password_login' in read-only section
.text'
/usr/bin/ld: /tmp/ccKZpQvi.o: in function inmenu': /home/legacy/Documents/project/src/../include/inmenu.h:27: undefined reference to
password_login'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
collect2: error: ld returned 1 exit status
This error goes away when i re-declare char *password_login in inmenu.h
But then segmentation fault occurs as the original value of password_login from login.h is lost and password_login points to 0x0 memory address and i use strcat() to concatenate password_login to another string.
How do i retain the value of password_login pointer in inmenu from login.
this is the concatsqluppass function
char *concatsqluppass(char *tmppass, char *tmppassnew)
{
char *sql;
sql = (char *)calloc(MAX, sizeof(char));
strcat(sql, "update user_list set encpass = '");
strcat(sql, tmppassnew);
strcat(sql, "'");
strcat(sql, " where encpass = '");
strcat(sql, tmppass);
strcat(sql, "'");
strcat(sql, "\0");
printf("query to be passed, \"%s\"", sql);
return sql;
}
Upvotes: 0
Views: 581
Reputation: 181
There’s a difference between declaring a variable and defining a variable. A variable can be declared at least once (but more is allowed). A variable can be defined once and only once.
When you do extern int x
you are declaring a variable. This says “this variable exists. I didn’t make it, someone else did. Just letting you know it exists“.
When you do int x
you are declaring and defining a variable. This says “I just made this variable. I created memory for it to live in. It exists. If you can see this statement you can use this variable”
If you put a definition (int x
) in a header, chances are you’ll define a variable more than once, as multiple files will #include
that file.
This is why you should put the definition (int x
) in the cpp file, as noone should #include
a cpp. If other files need to also use the variable, a declaration (extern int x
) can also go in the header file.
Doing this, you can put extern char *password_login
in as many headers as you want and use the variable on those files.
Upvotes: 2
Reputation: 107
define password in login object file and define that same variable in imenu object file as
extern char * password_login
...
...
function(password_login,...);
make sure to use object file rather than writing code in header files.
Upvotes: 0