C++ header file: error: expected unqualified-id before ')' token

C++ header file: error: expected unqualified-id before ')' token

很抱歉问了这样一个初学者问题,但我一直在写头文件。有关信息,没有与我遇到的问题相关的 Whosebug 文章——似乎我有一个非常简单的设置错误,但在互联网上找不到它。

错误信息:

insertion/insertion.h:16:24: error: expected unqualified-id before ')' token   
   16 |         void insertion();

insertion.cpp:

#include <insertion.h>
// more imports

void insertion() {
    // implementation not shown
}

int main() {
    insertion();
    return 0;
}

insertion.h:

#include <iostream>
// exactly the same imports as the file above but didn't import itself

#ifndef insertion
#define insertion

class Insertion {
    public:
        void insertion();
};

#endif 

execute.cpp:

#include "insertion/insertion.h"
using namespace std;

int main() {
    // still writing
}

文件结构如下所示:

|- execute.cpp
|- insertion\
|---- insertion.cpp
|---- insertion.h

非常感谢任何帮助。

#define insertionvoid insertion(); 相撞。

改变

#ifndef insertion
#define insertion

#ifndef _insertion_h_inc_
#define _insertion_h_inc_

或更好:改变

#include <iostream>
// exactly the same imports as the file above but didn't import itself

#ifndef insertion
#define insertion

class Insertion {
    public:
        void insertion();
};

#endif 

#ifndef _insertion_h_inc_
#define _insertion_h_inc_

#include <iostream>
// exactly the same imports as the file above but didn't import itself

class Insertion {
    public:
        void insertion();
};

#endif 

#define insertion

是您遇到问题的原因。

insertion 之后的所有地方都被一个空标记替换。


class Insertion {
    public:
        void insertion();
};

变成

class Insertion {
    public:
        void ();
};

void insertion() {
    // implementation not shown
}

int main() {
    insertion();
    return 0;
}

变成

void () {
    // implementation not shown
}

int main() {
    ();
    return 0;
}

现在您可以了解您的程序编译失败的原因了。

改变

#ifndef insertion
#define insertion

#ifndef insertion_h
#define insertion_h

这应该可以解决您的问题。


更好的是,使用#pragma once。大多数现代编译器都支持它。

#pragma once

#include <iostream>

class Insertion {
    public:
        void insertion();
};

我总是在我的代码上这样做

insertion.h

#pragma once
#ifndef insertion_h
#define insertion_h
//some codes goes here
#endif

在我的 main.cpp 文件中

#include "insertion.h"

一切顺利,希望对您有所帮助。

此致,

乔伊

编辑: 如果你想了解更多关于 pragma 的信息,你可以参考这个 link 这里 more on pragma's