Try to strip the project path from __FILE__

following code (main.cpp):

#include <string>
#include <vector>

std::vector< std::string > split( std::string haystack, const char limiter ) {
    std::vector< std::string > return_value;

    while( haystack.find( limiter ) != std::string::npos ) {
        return_value.push_back( haystack.substr( 0, haystack.find( limiter ) ) );
        haystack = haystack.substr( haystack.find( limiter ) + 1 );
    }

    return_value.push_back( haystack );

    return return_value;
}

const char* str = split( std::string( __FILE__ ), '/' ).back().c_str();

int main() {
    printf( "%s\n", str );
    return 0;
}

It always returns "iso_a3", and I donโ€™t know why ... Basically, what I want to do is define a LOG macro that displays the file name and at the beginning calculates the length of the projectโ€™s base directory to subtract it for example: __FILE__[ _base_directory_length ]to exit was more readable, to be precise:

debug.h

#pragma once

static int _base_directory_length = strlen( __FILE__ ) - split( __FILE__, '/' ).back().length();

#define LOG( message ) { \
    printf( "%s(%i): %s ", __FILE__ + _base_directory_length, __LINE__, __func__ ); \
    printf( message ); \
    printf( "\n" ); \
}

It makes sense:-)? BTW is _base_directory_length = strlen( __FILE__ ) - strlen( "Debug.h" )not enough.

+4
source share
3 answers

__FILE__[ _base_directory_length ] will return a single character.

Perhaps you want to &__FILE__[ _base_directory_length ]. '

0
source

Well, I wish I bothered, should have been more attentive. This is what I really wanted to do:

Debug.cpp :

#include <cstring>

/* calculate the length of the root directory string */
int _path_length = strlen( __FILE__ ) - strlen( strrchr( __FILE__, '/' ) ) + 1;

debug.h

extern int _path_length;

#define LOG( message ) {
    printf( "%s(%i): %s:\t", __FILE__ + _path_length, __LINE__, __func__ );
    printf( message ); /* message may be a variadic list of arguments */
    printf( "\n" );
}

, Debug.cpp .

, .

0

Seems strange. I copy the first piece of code and run my host, I have "main.cpp".

Why not do some debugging? If you want to use gdb, you can just type str and each element that you put in return_value.

0
source

All Articles