问题描述
- error LNK2019: 无法解析的外部符号 _add,该符号在函数 _main 中被引用
-
如果把所有的.cpp文件改成.c,程序正常运行。我认为加上extern "C"应该可以正常运行了,但是不行,求解 原理。student.h
struct Student { char name[30]; int score; struct Student *next; }; typedef struct Student Stu; typedef struct Student * Pstu; #ifdef __cplusplus extern "C" { #endif void add(Stu** head, char* name, int score); void showall(Pstu head); Pstu reverse(Pstu head); int getNum(Pstu head); Pstu getStu(Pstu head, int score); int change(Pstu head, int oldscore, int newscore); void freeall(Pstu head); #ifdef __cplusplus } #endif
Student.cpp
#include"student.h" #include<stdio.h> #include<stdlib.h> #include<string.h> #ifdef __cplusplus extern "C"{ #endif void add(Stu** head, char* name, int score) { Pstu p1 = *head; Pstu p2 = (Pstu)malloc(sizeof(Stu)); strcpy(p2->name, name); p2->score = score; p2->next = p1; *head = p2; } void showall(Pstu head) { Pstu p = head; while (p) { printf("%s,%d", p->name, p->score); p = p->next; } } #ifdef __cplusplus } #endif
main.cpp
#include"student.h" #include<stdio.h> #include<stdlib.h> int main() { Pstu head = NULL; add(&head, "zz", 90); add(&head, "ymt", 100); //showall(head); return 0; }
解决方案
如果不是调用已经编译好的c函数,我觉得没有必要使用extern c
参考:什么情况下需要使用externc
http://my.oschina.net/xlplbo/blog/330593
解决方案二:
等于cpp调用c函数,调用约定有区别。
解决方案三:
你的代码在vs2013中编译通过
如果全部改成.c,函数是用c的方式编译,在c的main函数中以c的方式调用应该没什么问题
全部改成.cpp,在main中以cpp的方式调用c函数,不同编译器可能就会出错,这时候不能用#include"student.h",试试用extern "C" int add()可能就会解决问题
解决方案四:
无论是用控制台还是空项目,我都可以编译通过,除了注意那个strcpy的安全性检查error
我觉得控制台和空项目是一样的,只不过自动添加了一个stdafx.h和helloworld,其他没有本质区别
你可以自己打开空项目和控制台程序的所有配置文件仔细比较下,我粗略看了一下没有什么区别
时间: 2024-08-04 04:05:05