VC调用matlab函数mclcppMlfFeval重复定义

问题背景:
用mcc -W cpplib:libname -T link:lib -v matlab_m_file.m
编译.m文件,生成vc可用的动态连接库和.h头文件,相关数据.c文件,和一个.cpp文件(m_to_cpp.cpp),该.cpp文件中.h文件提供的各个接口的实现,它包括在VC程序中应用matlab连接库时所需的初始化函数,结束时的资源回收函数,以及由.m文件生成的函数接口等。
现在我们就可以把生成的这几个文件加到我们的工程中,利用.h文件提供的接口来调用原.m文件中的函数。

问题描述:
若自己另写一个源文件(比如main.cpp),因为我们要在其中调用.m文件中函数,所以要include进上述生成的.h文件。
此时,在编译器链接时会报错:main.obj和m_to_cpp.obj中的mclcppMlfF重复定义
LNK2005: void __cdecl mclcppMlfF multiply defined

产生原因:
究其原因,发现在main.cpp和m_to_cpp.cpp最终都会include一个matlab的头文件mclcppclass.h,而在mclcppclass.h中有mclcppMlfF的实现代码,它是类mwArray的一个友元函数。
当然在链接的时候会发现两个mclcppMlfF的实现,就会报重复定义错误了。
http://newsgroups.derkeiler.com/Archive/Comp/comp.soft-sys.matlab/2005-12/msg03204.html
Maybe the "mclcppclass.h" is not good.(<matlab>\extern\include\)
First part of this head is the definition of class "mwArray", another
part is the definition of function "mclcppMlfF". The later is
the "friend" of the class mwArray.
When doing some simple examples, it work fine. But if the VC Project
is complex,-- several .cpp files need to include this head. It often
make the error :
"<1>.obj : error LNK2005:
"void __cdecl mclcppMlfF(void *,char const *,int,int,int,...)"
(?mclcppMlfF@@YAXPAXPBDHHHZZ) already defined in <2>.obj"

I solved this problem by dividing this head into two files,defining
mwArray and mclcppMlfF separately.
Notice: Don't delete the original "mclcppclass.h". The compile need it.
(Here, use " mcc -B cpplib:< > < .m>" to generate the C++
shared library.)

Another, to generate the C++ shared library, Matlab 7.1 makes
"LIB_wave1_C_API" and "LIB_wave1_CPP_API " in the <lib>.h. It
can make the:
"wave1.lib(wave1.dll) : error LNK2005: "void __cdecl
wavedetect1(int,class mwArray &,class mwArray const &)"
(?wavedetect1@@YAXHAAVmwArray@@ABV1@@Z) already defined in wave1.obj"

If only want to generate the C++ shared library, it's unneccessary to
generate the "LIB_wave1_C_API" part , I suppose!

解决办法:
我的解决办法是:在mclcppclass.h 中添加
#ifndef OMT_mclcppMlfF
void mclcppMlfF ...
...
...
#endif
即将函数mclcppMlfF的实现用一个预编译宏包含起来。
然后在我们自己的源文件(main.cpp)的开始处加上
#define OMT_mclcppMlfF
使mclcppMlfF的函数实现不会编译进我们自己的源文件的.obj中

你可能感兴趣的:(api,matlab,Class,include,library,编译器)