Issue
I have compiled a C program with a shared library. I do not understand why
$ LD_LIBRARY_PATH=<path_to_lib> ./a.out
works; yet
$ LD_LIBRARY_PATH=<path_to_lib>
$ ./a.out
does not.
The two-line approach sometimes worked for me before. So I feel confused.
Solution
I'm assuming you meant LD_LIBRARY_PATH, but either way, the answer is the same:
There are two types of variables that are relevant in this context:
- Non-environment variables, which are set in the current shell's context and do not persist into subshells. Sometimes these are called "shell variables" or "local variables", but those terms can have other meanings.
- Environment variables, which are set in the current shell and persist into the context of subshells spawned from the current shell. They can be displayed with the "env" command.
The first (one-liner) command in your post sets LD_LIBRARY_PATH as an environment variable, but only for the invocation of a.out that's on the same line. a.out runs in a subshell and can see the value of LD_LIBRARY_PATH (because it's an environment variable). After a.out finishes, the LD_LIBRARY_PATH that was set goes out of scope.
The second set of commands sets LD_LIBRARY_PATH as a non-environment variable, which means the variable is available in the current shell only. Because a.out runs in a subshell when you call it, it won't see the value of LD_LIBRARY_PATH. You would need to precede the LD_LIBRARY_PATH=<path_to_lib> with an "export" to make it an environment variable, as shown below.
$ cat ./a.out
#!/bin/bash
env | grep LD_LIBRARY_PATH
echo $LD_LIBRARY_PATH
# LD_LIBRARY_PATH is treated as an environment variable
$ LD_LIBRARY_PATH=/usr/lib ./a.out
LD_LIBRARY_PATH=/usr/lib
/usr/lib
# LD_LIBRARY_PATH is NOT set as an environment variable
$ LD_LIBRARY_PATH=/usr/lib
$ ./a.out
# "export" sets LD_LIBRARY_PATH as an environment variable
$ export LD_LIBRARY_PATH
$ ./a.out
LD_LIBRARY_PATH=/usr/lib
/usr/lib
$
Answered By - cdub Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.