错误C2059:语法错误:'字符串'

Error C2059: syntax error : 'string'

本文关键字:错误 字符串 语法 C2059      更新时间:2023-10-16

我看过其他帖子,老实说,我仍然不确定是什么导致了问题。我在Visual Studio和中编程

我有以下代码:(这是一个C主)

int main(int arc, char **argv) {
       struct map mac_ip;
       char line[MAX_LINE_LEN];
       char *arp_cache = (char*) calloc(20, sizeof(char));   //yes i know the size is wrong - to be changed
       char *mac_address = (char*) calloc(17, sizeof(char));
       char *ip_address = (char*) calloc(15, sizeof(char));
       arp_cache = exec("arp -a", arp_cache);

它使用以下cpp代码:

#include "arp_piping.h"
extern "C" char *exec(char* cmd, char* arp_cache, FILE* pipe) {
    pipe = _popen(cmd, "r");
    if (!pipe) return "ERROR";
    char buffer[128];
    while(!feof(pipe)) {
        if(fgets(buffer, 128, pipe) != NULL) {
              strcat(arp_cache, buffer);
        }
    }
    _pclose(pipe);
    return arp_cache;
}

具有匹配的头文件:

#ifndef ARP_PIPING_H
#define ARP_PIPING_H
#endif
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
#include <stdio.h>
#include <string.h>
extern "C" char *exec(char* cmd, char* arp_cache, FILE* pipe);
#undef EXTERNC

但我不断得到以下错误:

1>d:arp_protoarp_protoarp_piping.h(14): error C2059: syntax error : 'string'
1>main.c(22): warning C4013: 'exec' undefined; assuming extern returning int
1>main.c(22): warning C4047: '=' : 'char *' differs in levels of indirection from 'int'

请给我一些帮助,我已经看了其他关于c2059的帖子,但仍然一无所获

更改exec声明以使用您煞费苦心定义的EXTERNC宏。

EXTERNC char *exec(char* cmd, char* arp_cache, FILE* pipe);

我在向项目添加enum时遇到了此编译错误。事实证明,enum定义中的一个值与预处理器#define有名称冲突。

enum看起来如下:


// my_header.h
enum Type 
{
   kUnknown,
   kValue1,
   kValue2
};

然后在其他地方有一个#define,它包含以下内容:


// ancient_header.h
#define kUnknown L"Unknown"

然后,在项目中其他地方的.cpp中,包含了这两个标题:


// some_file.cpp
#include "ancient_header.h"
#include "my_header.h"
// other code below...

由于名称kUnknown已经是#define'd,当编译器在我的enum中使用kUnknown符号时,它生成了一个错误,因为该符号已经用于定义字符串。这导致了我看到的神秘的syntax error: 'string'

这令人难以置信地困惑,因为enum定义中的所有内容似乎都是正确的,并且它自己编译得很好。

这是在一个非常大的C++项目中进行的,#define被过渡地包含在一个完全独立的编译单元中,并且是由15年前的某个人编写的,这也于事无补。

显然,从这里开始,正确的做法是将可怕的#define重命名为比kUnknown更不常见的值,但在此之前,只需将enum值重命名为其他值即可修复,例如:


// my_header.h
enum Type 
{
   kSomeOtherSymbolThatIsntDefined,
   kValue1,
   kValue2
};

无论如何,希望这个答案对其他人有帮助,因为这个错误的原因让我困惑了一天半。

extern"C"用于告诉编译器将其作为C语法,但您的意思是删除名为exec的extern函数。你只是把不同的东西融合在一起。所以在arp_piping.h:中这样重写代码

/*extern "C"*/ char *exec(char* cmd, char* arp_cache, FILE* pipe);

然后在cpp文件中del外部"C"的前缀。如果你想用C语法来调试它们,只需在调用函数exec的cpp中进行设置,就可以这样写:

extern "C" {
   #include "arp_piping.h"
}