반응형
함수 이름을 문자열로 가져옵니다.
제가 전화하는 기능의 이름을 표시하고 싶습니다.여기 내 코드가 있습니다.
void (*tabFtPtr [nbExo])(); // Array of function pointers
int i;
for (i = 0; i < nbExo; ++i)
{
printf ("%d - %s", i, __function__);
}
사용했습니다.__function__
예를 들어 제가 원하는 것과 꽤 가깝기 때문입니다만, 저는 다음과 같이 가리키는 기능의 이름을 표시하고 싶습니다.tabFtPtr [nbExo]
.
도와주셔서 감사합니다 :)
당신은 C99 표준 이상을 따르는 C 컴파일러가 필요합니다.다음과 같은 미리 정의된 식별자가 있습니다.__func__
당신이 원하는 걸 해주는 거지
void func (void)
{
printf("%s", __func__);
}
편집:
궁금한 참고 사항으로 C 표준 6.4.2.2는 위의 내용이 명시적으로 다음과 같은 내용을 기재한 것과 완전히 동일하다는 것을 지시합니다.
void func (void)
{
static const char f [] = "func"; // where func is the function's name
printf("%s", f);
}
편집 2:
따라서 함수 포인터를 통해 이름을 얻기 위해 다음과 같은 것을 구성할 수 있습니다.
const char* func (bool whoami, ...)
{
const char* result;
if(whoami)
{
result = __func__;
}
else
{
do_work();
result = NULL;
}
return result;
}
int main()
{
typedef const char*(*func_t)(bool x, ...);
func_t function [N] = ...; // array of func pointers
for(int i=0; i<N; i++)
{
printf("%s", function[i](true, ...);
}
}
이게 당신이 원하는 것인지는 모르겠지만, 당신은 이런 일을 할 수 있습니다.함수 이름과 주소, 함수 배열을 파일 범위에 저장할 구조를 선언합니다.
#define FNUM 3
struct fnc {
void *addr;
char name[32];
};
void (*f[FNUM])();
struct fnc fnames[FNUM];
함수 이름(예: 함수 이름)을 사용하여 코드의 초기화를 수동으로 수행합니다.
fnames[0] = (struct fnc){foo1, "foo1"}; // function address + its name
fnames[1] = (struct fnc){foo2, "foo2"};
fnames[2] = (struct fnc){foo3, "foo3"};
배열을 검색하는 기능을 만듭니다.
char *getfname(void *p)
{
for (int i = 0; i < FNUM; i++) {
if (fnames[i].addr == p)
return fnames[i].name;
}
return NULL;
}
이것에 대한 간단한 테스트를 해봤습니다.배열을 초기화했습니다main
, 하고 전화를 했습니다.foo1()
. 제 기능과 출력은 다음과 같습니다.
void foo1(void)
{
printf("The pointer of the current function is %p\n", getfnp(__func__));
printf("The name of this function is %s\n", getfname(getfnp(__func__)));
printf("The name of the function at pointer f[2] (%p) is '%s'\n", f[2],
getfname(f[2]));
}
The pointer of the current function is 0x400715
The name of this function is foo1
The name of the function at pointer f[2] (0x40078c) is 'foo3'
또는 일반적으로 다음과 같습니다.
void foo2(void)
{
for (int i = 0; i < FNUM; i++) {
printf("Function f[%d] is called '%s'\n", i, getfname(f[i]));
}
}
Function f[0] is called 'foo1'
Function f[1] is called 'foo2'
Function f[2] is called 'foo3'
언급URL : https://stackoverflow.com/questions/15349761/get-called-function-name-as-string
반응형
'programing' 카테고리의 다른 글
수행 표시줄의 텍스트를 변경하는 방법 (0) | 2023.10.20 |
---|---|
이름에 panda DataFrame의 특정 문자열이 포함된 열을 삭제합니다. (0) | 2023.10.20 |
기존 SQLite 테이블에 외부 키를 추가하려면 어떻게 해야 합니까? (0) | 2023.10.15 |
태그가 필요한 항목에 대한 워드프레스 위젯 업데이트 인스턴스 (0) | 2023.10.15 |
HTML 테이블에서 테두리를 완전히 제거하는 방법 (0) | 2023.10.15 |