新手求助, error: template with C linkage

2019-08-18 10:15:32 +08:00
 xwbz2018

g++版本7.4.0

编译命令
g++ -c -std=c++11 -O3 -o myport myport.cpp -lrt -lpthread -Icore -Lcore

报错部分:

In file included from /usr/include/ctype.h:39:0,
                 from /usr/include/c++/7/cctype:42,
                 from /usr/include/c++/7/bits/localefwd.h:42,
                 from /usr/include/c++/7/string:43,
                 from core/***.h:26,
                 from core/***.h:4,
                 from myport.cpp:4:
core/***.h:29:1: error: template with C linkage
 template<bool ToLittle>
 ^~~~~~~~
In file included from core/***.h:30:0,
                 from core/***.h:4,
                 from myport.cpp:4:
/usr/include/netinet/tcp.h:102:17: error: redeclaration of ‘ uint8_t tcphdr::<unnamed union>::<unnamed struct>::th_off ’
  uint8_t th_off:4; /* data offset */
                 ^
/usr/include/netinet/tcp.h:99:17: note: previous declaration ‘ uint8_t tcphdr::<unnamed union>::<unnamed struct>::th_of ’
  uint8_t th_off:4; /* data offset */
                 ^
/usr/include/netinet/tcp.h:103:16: error: redeclaration of ‘ uint8_t tcphdr::<unnamed union>::<unnamed struct>::th_x2 ’
  uint8_t th_x2:4; /* (unused) */
                ^
/usr/include/netinet/tcp.h:98:16: note: previous declaration ‘ uint8_t tcphdr::<unnamed union>::<unnamed struct>::th_x2 ’
  uint8_t th_x2:4; /* (unused) */

由于强行转的 c/c++,很多基础不知道,来求助一下大佬们。迫于保密,部分已打码。

看描述有两个问题:

1. error: template with C linkage

搜了下,这个很多是 extern "C"导致的,我这边的是:

#ifdef __cplusplus
extern "C" {
#endif
#include "myport.h"
#ifdef __cplusplus
}
#endif

整段去掉都没用

2. 报错地点引用了以下头文件

#include <string>
#include <strings.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>       <-- 这行是 core/***.h:30:0
#include <arpa/inet.h>
4868 次点击
所在节点    C
9 条回复
ipwx
2019-08-18 10:47:07 +08:00
似乎是你引用的头文件和你的明明冲突了。

建议把 TCP 相关代码封装到一个类里面,然后通过 .h & .cpp 隔离 netinet/tcp.h,不污染你程序别的地方。
xwbz2018
2019-08-18 11:13:30 +08:00
@ipwx 谢谢,我试下看看。不过除了自己写的 myport.cpp ,其他都是.h 文件
Nasei
2019-08-18 11:20:47 +08:00
string
xwbz2018
2019-08-18 11:31:26 +08:00
@Nasei ???是哪里写错了吗?
pagxir
2019-08-18 11:31:47 +08:00
#ifdef __cplusplus
extern "C" {
#endif
#include "myport.h"
#ifdef __cplusplus
}
#endif
把这里的 extern c 去掉,因为 extern c 表明代码是 c 的代码,但是你的 myport.h 却使用了模板,这明显是 cpp 的代码。这不是自相矛盾么
xwbz2018
2019-08-18 11:37:29 +08:00
@pagxir #5 myport. h 里面就定义了结构体和方法,没有 template,连导入头文件都没有,template 是 core 文件夹里的一个头文件定义的,而且我把 extern 删掉都一样的结果
pagxir
2019-08-18 11:42:31 +08:00
那就是你文件名命名有问题,跟系统头文件冲突了
xwbz2018
2019-08-18 11:51:57 +08:00
@pagxir 谢谢,我看看是不是
xwbz2018
2019-11-21 14:00:13 +08:00
@pagxir #7 的确是跟 /usr/include/ctype.h 里引用的系统头文件重名了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/592827

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX