clinuxrhelgetenv

C program getenv() returns null despite terminal echo working


I have read all the other posts with the same title, but I'm not on an embedded system, and I have my includes and environment variable set correctly. Running on RHEL 7.5, my program with getenv wasn't working so I created a C application with the simple functionality of printing the JAVA_HOME environment variable. It returns null from the C program but the environment variable is set (has been set permanently) and reads fine in my putty terminal. This is exactly what I'm running (just the paths shortened):

C:

#include <stdio.h>
#include <stdlib.h>

int main () {
   printf("JAVA HOME : %s\n", getenv("JAVA_HOME"));

   return(0);
}

makefile:

CC=gcc
CFLAGS=-c -Wall -I/path/to/includes
BIN=/path/to/bin

INCLUDE=/path/to/includes

default : $(BIN)/testEnv


testEnv.o : testEnv.c
    $(CC) $(CFLAGS) testEnv.c

#------------ Make testEnv-------------------
$(BIN)/testEnv: testEnv.o
    $(CC) -o $@  \
    testEnv.o

Terminal:

>bin/testEnv
JAVA HOME : (null)
>echo $JAVA_HOME
/path/to/java

Does anyone have anything new I should check or know what the issue could be? Thanks.


Solution

  • Your JAVA_HOME variable is likely a shell variable, not exported one. Be sure to export it before starting your app from this shell:

    export JAVA_HOME