简体   繁体   English

printf函数中的点和const

[英]The dots and const in printf function

I wrote the following code in c++: 我用c ++编写了以下代码:

int printf(const char *p,...);
int main()
{
    printf("Stack Overflow\n");
    return 0;
}

It returned an error : 它返回一个错误:

/home/tWi2Su/ccnhXznj.o: In function `main':
prog.cpp:(.text.startup+0x17): undefined reference to `printf(char const*, ...)'
collect2: error: ld returned 1 exit status

But when I remove the const , I get the following error : 但是当我删除const ,出现以下错误:

prog.cpp: In function 'int main()':
prog.cpp:4:27: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
  printf("Stack Overflow\n");
                           ^
/home/a5vnrT/cclz99Yy.o: In function `main':
prog.cpp:(.text.startup+0x17): undefined reference to `printf(char*, ...)'
collect2: error: ld returned 1 exit status

If I remove the dots , I get the following error : 如果删除dots ,则会出现以下错误:

/home/3jQpK8/cc01lRrz.o: In function `main':
prog.cpp:(.text.startup+0x17): undefined reference to `printf(char const*)'
collect2: error: ld returned 1 exit status

Compilation error   time: 0 memory: 0 signal:0

prog.cpp: In function 'int main()':
prog.cpp:4:27: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
  printf("Stack Overflow\n");
                           ^
/home/a5vnrT/cclz99Yy.o: In function `main':
prog.cpp:(.text.startup+0x17): undefined reference to `printf(char*, ...)'
collect2: error: ld returned 1 exit status

Why is it necessary to give dots here when I am the one declaring the function (and not predifining it). 当我是一个声明函数(而不是预先定义函数)的人时,为什么需要在此处加点。 Moreover when we pass a string to a function in c++, we do not need to mention const . 此外,当我们将字符串传递给c ++中的函数时,我们无需提及const Then why is necessary to give the const keyword here? 那为什么要在这里给const关键字呢?

In your case, 就你而言

int printf(const char *p, ...);
int main()
{
    printf("Stack Overflow\n");
    return 0;
}

you only have a declaration , no definition of printf() . 您只有一个声明 ,没有printf()定义。 Linker is shouting. 链接器正在大喊。

Regarding the (missing) const type-qualifier, in C++ , a string literal, (narrow string literals) has a type “array of n const char ”, and when you try to pass that to a char * , type mismatch happens. 关于(缺失的) const类型限定符,在C++ ,字符串文字((窄字符串文字)的类型为“ n const char数组”),当您尝试将其传递给char * ,会发生类型不匹配的情况。

That said, those dots, ... are used as the notation of a variadic function which can accept variable number of arguments. 就是说,这些点...用作可变参数函数的表示法,可以接受可变数量的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM