如果我在名为ppmformat.h的文件中声明一个函数
//file ppmformat.h
namespace imaging
{
Image * ReadPPM(const char * filename);
} //namespace imaging
...并在ppmformat.cpp
中定义它static imaging::Image * imaging::ReadPPM(const char *filename)
{
....
}
我收到以下错误:
'imaging :: Image * imaging :: ReadPPM(const char *)'被声明为'extern',后来被称为'static'[-fpermissive]
//ppmformat.h
#ifndef _PPM
#define _PPM
#include "Image.h"
namespace imaging
{
/*! Reads a PPM image file and returns a pointer to a newly allocated Image object containing the image.
*
* \param filename is the null-terminated string of the name of the file to open.
*
* \return a pointer to a new Image object, if the read operation was successful, nullptr otherwise.
*/
Image * ReadPPM(const char * filename);
} //namespace imaging
#endif
//ppmformat.cpp
#include <iostream>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include <string>
#include <fstream>
#include "ppmformat.h"
using namespace std;
imaging::Image * imaging::ReadPPM(const char *filename)
{
......
}
//Image.h
#ifndef _IMAGE
#define _IMAGE
#include "Color.h"
#include <iostream>
namespace imaging
{
class Image
{
....
}
}
//Image.cpp
#include <iostream>
#include "Color.h"
#include "Image.h"
....
//end of Image.cpp
//Color.h
#ifndef _COLOR
#define _COLOR
namespace imaging
{
Class Color
{
....
}
}
答案 0 :(得分:2)
声明具有不同链接的同一实体的代码无效。
C ++11§7.11/ 8(dcl.std / 8):“对特定实体的连续声明所暗示的联系应予以同意。也就是说,在给定的范围内, 声明相同变量名称或函数名称相同重载的每个声明都应表示 相同的联系。但是,给定的一组重载函数中的每个函数都可以具有不同的链接。
对于实践中,g ++ 5.1.4拒绝编译它,而不幸的是,Visual C ++ 2015将其作为语言扩展接受,并带有警告:
[C:\my\forums\so\257] > g++ foo.cpp foo.cpp: In function 'imaging::Image* imaging::ReadPPM(const char*)': foo.cpp:9:62: error: 'imaging::Image* imaging::ReadPPM(const char*)' was declared 'extern' and later 'static' [-fpermissive] static imaging::Image * imaging::ReadPPM(const char *filename) ^ foo.cpp:5:13: note: previous declaration of 'imaging::Image* imaging::ReadPPM(const char*)' Image * ReadPPM(const char * filename); ^ foo.cpp: At global scope: foo.cpp:9:54: warning: unused parameter 'filename' [-Wunused-parameter] static imaging::Image * imaging::ReadPPM(const char *filename) ^ [C:\my\forums\so\257] > cl foo.cpp foo.cpp foo.cpp(10): warning C4211: nonstandard extension used: redefined extern to static foo.cpp(9): warning C4100: 'filename': unreferenced formal parameter foo.cpp(9): warning C4505: 'imaging::ReadPPM': unreferenced local function has been removed [C:\my\forums\so\257] > _
如果编译器接受此警告,则最好将该警告变为硬错误。使用Visual C ++,可以选择/we4211
。