Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a cpp __DIR__ macro, similar to __FILE__

The __FILE__ and __LINE__ macros are built into the C Pre-Processor, and are often used for printing debug output with file names and line numbers. I need something similar, but with just the name of the directory at the end of the path. For instance if my code is in: /home/davidc/some/path/to/some/code/foo/bar I need a macro that will just give me "bar", if the code is in /home/davidc/some/path/to/some/code/foo/bee then I need it to give me "bee".

Any thoughts? (btw, this is for a C++ application).

Update: to be clear, I'm after a macro that will give me a string containing the directory name at compile-time, I don't want to do any string-processing at runtime.

like image 976
David Claridge Avatar asked Oct 20 '09 00:10

David Claridge


People also ask

What is __ file __ in C++?

__FILE__ is a preprocessor macro that expands to full path to the current file. __FILE__ is useful when generating log statements, error messages intended for programmers, when throwing exceptions, or when writing debugging code.

How do I create macros in CPP?

The naïve way to write the macro is like this: #define MACRO(X,Y) \ cout << "1st arg is:" << (X) << endl; \ cout << "2nd arg is:" << (Y) << endl; \ cout << "Sum is:" << ((X)+(Y)) << endl; This is a very bad solution which fails all three examples, and I shouldn't need to explain why.

What is the type of __ file __?

The __file__ variable: __file__ is a variable that contains the path to the module that is currently being imported.

What is macro in C++ with example?

A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro. Macro definitions need not be terminated by a semi-colon(;).


1 Answers

If you are using GNU make to build your project, then you might be able to do something like this:

%.o: %.cpp
    $(CC) $(CFLAGS) -D__DIR__="$(strip $(lastword $(subst /, , $(dir $(abspath $<)))))" -c $< -o $@

That has to be about the most God-awful thing that I have thought about doing in a Makefile in quite a while. I don't think that you will find a quick or clean way to do this within the confines of the compiler so I'd look for clever ways to inject the information into the compilation process.

Good luck.

like image 86
D.Shawley Avatar answered Sep 17 '22 23:09

D.Shawley