Environment variabile in Macro path - c

I need to define some path to files with macros. How can I use the $HOME environment variable?
I can't find it on the GNU manual, and this doesn't work:
#define LOGMMBOXMAN "$HOME/mmbox/LOGmmboxman"

No it shouldn't and you probably don't want constant-defined settings like that in any case. If you did that and it worked as you're intending to use it, your home directory would be built in as whatever $HOME is for whoever's doing the building. The executable then depends on that specific home directory existing. If that's OK, just #define your own home. I suspect it isn't though, so you need to deduce it at runtime.
For run-time deduction what you want is this, such that:
const char* home_dir = getenv("HOME");
If there is no $HOME defined, you get NULL returned so be sure to test for this.
You can then build your string based on that. You'll need #include <stdlib.h>.

Sounds like you are really asking "how can I set some cpp macro from my environment?"
If sothen you should just be able to add it to CPPFLAGS.
export CPPFLAGS="$CPPFLAGS -D LOGMMBOXMAN=$HOME/mmbox/LOGmmboxman"
Then in your code
#ifndef LOGBOXMAN
#error LOGBOXMAN not defined
#endif
Then make sure your source is built using the CPPFLAGS in the command line to gcc:
$ gcc -c file.c $CPPFLAGS

You can't. You need to use your build system to define a macro with the $HOME value (or equivalent on a non-unix system), i.e. something like this:
gcc -DHOME="/home/username" file.c
Or "/Users/username" for Mac OS X, or "C:\Users\username" (or something) for Windows. Basically, GCC provides the -D flag to define a macro on the command line. You can set up a script (or your build system) to take care of this macro definition for you, or perhaps make a system-dependent include file to define the HOME macro properly.
Then, in your C header, you can do:
#define LOGMMBOXMAN HOME "/mmbox/LOGmmboxman"
Note that, in C, consecutive string literals are concatenated. So this macro expands to:
"/home/username" "/mmbox/LOGmmboxman"
Which C interprets as
"/home/username/mmbox/LOGmmboxman"
EDIT: All that thinking, and I didn't think! D'oh!
As others have pointed out, you probably don't want to do this. This will hard-code your program to work for one specific user's home directory. This will likely cause problems if you want each user to use your program, but for each to keep his (or her) own separate files.
Ninefingers' answer is what you're most likely looking for. In the event that you ever find yourself in need of the above technique (i.e. storing application files in a system-specific place) I will leave my answer unchanged, but I expect it won't help you here.

Related

How do I set include paths when not using an IDE so it isn't cumbersome

I've been trying to work without an IDE. Now I'm setting up a project that I had done
on stm32cubeIDE. I got to the point where I'm adding headers and such to the main.c file. In the IDE I was able to tell the IDE where to look for headers, like the driver folder or w/e I called it. Without IDE, I had to go and change the path in the #include statement such that
#include "cooldriver.h"
became
#include "driver/cooldriver.h"
Then,I also have to change cooldriver.c's path to point to the right path.
Is there a way to simplify this so I don't have to go through and change all the #includes and just keep what I had.
I'm working in linux env and using arm-none-eabi-gcc.
The path i have is like,
main.c
Makefile
drivers
Inc
driver1.h
driver2.h
Src
driver1.c
driver2.c
TLTR: I want to tell compiler where to look for header files without an ide and without rewriting all the include statements.
Thanks.
TLTR: I want to tell compiler where to look for header files without an ide and without rewriting all the include statements.
Among their many available command-line options, compilers accept some that tell them about paths to search for headers and external libraries. On UNIX-heritage systems, the traditional one for paths that #include should consider is -I. Your compiler's documentation will provide more detail.
The traditional approach would be to set one or more variables in your makefile to contain the wanted command-line flags, and to expand those variables where appropriate in your make recipes. Sticking with convention, I would use variable CPPFLAGS for -I and other flags directed toward the C preprocessor.

is it possible to use the preprocessor __file__ to generate a #define in C?

In order to improve the aesthetics of some code, I would like to have a .h file contain some code that sets a #define based on which file the .h file is included from. For example
#if (__file__ == "main.c")
#define MOUDLE MODULE_MAIN
#elif (__file__ == "foo.c")
#define MODULE MODULE_FOO
#endif
Is there any way to accomplish something like this? The main motivation is to avoid putting a #define MODULE at the top of every file and instead have one location where the mapping is defined and to just include the same .h file.
No, you can't do this. #if can only do integer expressions. It knows nothing about strings or how to compare them.
What you want is not possible with the standard C preprocessor. Check by reading the C standard, eg n1570, or some C reference, or the wikipage on the C preprocessor, or the GNU cpp manual.
But consider another way to achieve the same: configure appropriately your build automation.
For example, if you use make, then edit your Makefile appropriately. How to do that is a very different question.
You could have a rule for make which passes a specific -DMODULE=name to gcc
For example in my bismon (on github) the Makefile has near line 141 something similar to
modules/modbm_%.so: modules/modbm_%.c bismon.h $(GENERATED_HEADERS) $(BM_HEADERS)
$(CCACHE) $(LINK.c) -fPIC \
-DBISMON_MODID=$(patsubst modules/modbm_%.c,_%,$<) -shared $< -o $#
Be creative. The build machinery is part of your source code. Adapt it to do what you want. Don't expect the standard preprocessor to cover all your needs. Learn how to invoke GCC (or your favorite compiler) on the command line. In some cases, it is even worthwhile to generate some C file (perhaps some header file), and you might use another preprocessor (like GPP or m4) for that purpose.
Remember that the compiler (notably GCC and Clang) is a command line program, that you should drive from something else (like make, ninja or many other build automation tools).
(even on microsoft systems the compiler is still a command line thing, but that fact is often ignored)
BTW, I dislike many IDEs because they are hiding the build process, and you need to master it. So you need to configure it (e.g. by writing your Makefile or something else) and to understand and tailor it.
The main motivation is to avoid putting a #define MODULE at the top of every file and instead have one location where the mapping is defined
That single location defining such a mapping should probably be your build infrastructure (e.g. your Makefile if using make); you'll adapt it to invoke gcc or clang (or most other C compilers) with an appropriate -DMODULE=name flag. (BTW, you also want the convention that your base name of sources files are C identifiers, so you won't have any a-1.c file -since a-1 is not an identifier-, but a bcde.c one).
If using GNU make, read its documentation, then run make -p to understand the rules (both builtin, and custom) relevant to your case. Then consider perhaps a rule similar to:
%.o: %.c $(YOURHEADERS)
$(COMPILE.c) -DMODULE=$(patsubst %.c,MODULE_%,$^) -c $< -o $#
but adapt that rule to your needs. (you could need some $(shell ... ) inside it if your file names are lower cases, and you want upper case MODULE).
BTW, you could also generate parts of your Makefile (or have some generated C files, which you would #include appropriately).

How do I execute my program without ./a.out command?

I have written a c program. I want to pipe the program and I want to make it look meaningful. So instead of writing ./a.out each time, I want to name it changetext. To achieve that, I compiled my program following way: gcc -o changetext myprog.c. To the best of my knowledge, this should replace the use of ./a.out and changetext should do that instead. But I'm getting command not found. I am new to c and unix environment. Any suggestion appreciated.
As I said in a comment, you can either put a dot slash (./) in front of the executable to run it
./changetext
Or you put in in a directory that is referenced in the PATH environment variable. A nice explanation of this safety feature can be found here (thanks to rubenvb):
http://www.linfo.org/dot_slash.html
It says that this is more or less to distinguish built-in commands from user-written commands with the same name. I am not convinced though. The shell could simply prefer built-in names to user-supplied ones, and look in the current directory as well as in the PATH.
But this is the *nix way.
In order to compile and run a program such as your changetext with just the command chanhetext, you must put the binary in a directory listed in your PATH environment variable. It is recommended that you put programs that you made for your own use in the ~/bin/ directory. The command you would use to accomplish this would be the following, assuming ~/bin/ already exists:
gcc -o ~/bin/changetext myprog.c
If it does not exist, you can simply create it, then log out and back in.
If you are tired of doing the ./ before the program name you can always make an alias such as
alias a='./a.out' or alias changetext='./changetext'
this just basically look for everytime you type changetext or a and then replaces it to have the ./ infront of it

Running a C program in Linux

Can someone explain to me why, in particular, we are using ./a.out to run a program?
Is there any meaning behind this?
Can someone please provide an explanation?
The name stands for "assembler output", and was (and still is) the default name for the executable generated by the compiler. The reason you need ./ in front of it is because the current directory (.) is not in $PATH therefore the path to the executable must be explicitly given.
If you mean the ./ part, it's for safety. Windows by default appends current directory to PATH, which is bad (there's a risk of DLL injection, and so on).
If you mean a.out part, it's just a name (which came from name of format a.out), which you can change by modifying gcc -o parameter.
When running an executable like a shell like bash the executable must be in your PATH environment variable for bash to locate and run the program.
The ./ prefix is a shorthand way of specifying the full path to the executable, so that bash does not need to the consult the PATH variable (which usually does not contain the current directory) to run it.
[For a.out (short for "assembler output"), it is the default executable output for a compiler like gcc if no output filename is specified.]
It'd be worth you looking a bit more into C and the way that C programs are compiled.
Essentially, your source code is sent to the preprocessor, where directives like #define and #include are loaded (e.g. into memory). So any libraries you want to use are loaded, e.g.
#include <math.h>
will basically 'paste' the contents of math.h into source code at the point at which it is defined.
Once all this stuff has been expanded out, the compiler turns your source code into object code, which is your source in binary code. a.out is the default name for output if you do not specify a build name.
gcc -o mynewprogram mynewprogram.c
a.out is the default name for the compiler. AFAIK it is because the linking process is skipped and it is not compiled as an object or library.

gcc check if file is main (#if __BASE_FILE__ == __FILE__)

In ruby there's very common idiom to check if current file is "main" file:
if __FILE__ == $0
# do something here (usually run unit tests)
end
I'd like to do something similar in C after reading gcc documentation I've figured that it should work like this:
#if __FILE__ == __BASE_FILE__
// Do stuff
#endif
the only problem is after I try this:
$ gcc src/bitmap_index.c -std=c99 -lm && ./a.out
src/bitmap_index.c:173:1: error: token ""src/bitmap_index.c"" is not valid in preprocessor expressions
Am I using #if wrong?
As summary for future guests:
You cannot compare string using #if
BASE_FILE is the name of file that is being compiled (that Is actually what I wanted).
Best way to do this is to set flag during compilation with -D
in gcc you can use:
#if __INCLUDE_LEVEL__ == 0
or:
if(!__INCLUDE_LEVEL__)
to check if your inside the __BASE_FILE__
Yes, you are misusing #if. It only works on integer constant expressions. But even if you were using if, comparing pointers for equality is never a valid way to compare strings in C.
It seems you can't.
Alternatively, it works perfectly fine on a regular if condition, and gcc can optimize this nicely.
if (!strcmp(__BASE_FILE__, __FILE__)) {
// works.
}
but you can't define new main functions or use other preprocessor tricks. but you could short-circuit main by using static methods, but that's harsh and dirty.
But maybe you shouldn't do it. in Ruby/python, this works because usage of files is done at runtime. in C, all files are to be compiled to be used.
Keep in mind that most build system will build one file at a time, building them as object files, and rebuilding them only when necessary. So
__BASE_FILE__ and __FILE__
will be equals most of the time in sources files, if not always. And i would strongly discourage you to do this in header files.
It's easier to just put your tests in separate files, only linking them when needed.
Yup, as others say, you're misusing it since you can't compare strings that way in C, and especially not in the preprocessor.
The file that defines int main(int argc, char* argv[]) is the main file. There can be only one such function in an executable.
In addition to what others have said (you can't have the C preprocessor compare strings), be careful with __BASE_FILE__ because it may not correspond to your definition of "main" file. __BASE_FILE__ is the name of the file being compiled, so it's always equal to __FILE__ in source files, and only differs in headers and other included files.
In particular, __BASE_FILE__ is not the name of the file which contains the main() function.

Resources