Reputation: 23035
I have created a C++/CLI (Visual C++) project in visual studio 2010 professional. I then added a very small C++ class to the project. Followng is the code
#include <stdafx.h>
#include <iostream>
using namespace std;
class Tester
{
public:
Tester(){};
void show()
{
cout << "OKOK..Printing" << endl;
}
};
Now, I dragged and dropped a button to the automatically built GUI form, and I am about to call the above code from the button. Following is the code of the button.
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
Tester ^t = gcnew Tester();
//Test t; - giving errors as well
}
};
When I execute the code, I get the following error
1>------ Build started: Project: testdamn, Configuration: Debug Win32 ------
1>Build started 7/1/2013 12:59:38 PM.
1>InitializeBuildStatus:
1> Touching "Debug\testdamn.unsuccessfulbuild".
1>GenerateTargetFrameworkMonikerAttribute:
1>Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files.
1>ClCompile:
1> All outputs are up-to-date.
1> Test.cpp
1> testdamn.cpp
1>c:\users\yohan\documents\visual studio 2010\projects\testdamn\testdamn\Form1.h(79): error C2065: 'Tester' : undeclared identifier
1>c:\users\yohan\documents\visual studio 2010\projects\testdamn\testdamn\Form1.h(79): error C2065: 't' : undeclared identifier
1>c:\users\yohan\documents\visual studio 2010\projects\testdamn\testdamn\Form1.h(79): error C2061: syntax error : identifier 'Tester'
1> Generating Code...
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:01.86
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I also noticed when I removed the class call from the button, the program build fine. So, how can I call to these C++ classes from C++/CLI ?
Upvotes: 1
Views: 169
Reputation: 244981
Look at the compiler errors you're receiving:
1>c:\...\testdamn\Form1.h(79): error C2065: 'Tester' : undeclared identifier
1>c:\...\testdamn\Form1.h(79): error C2065: 't' : undeclared identifier
1>c:\...\testdamn\Form1.h(79): error C2061: syntax error : identifier 'Tester'
The compiler is telling you that it cannot find any class named Tester
and therefore cannot use it.
In order to use your Tester
class, you need to include the header file that contains its definition in the file that contains your Form class's definition. This is the same as how you had to include the iostream
header in order to use std::cout
.
But once you fix this, you'll have another problem: you're trying to use gcnew
to instantiate Tester
, which is an unmanaged class. gcnew
is intended to instantiate managed classes, and allocates memory from the managed heap. You want to use the regular C++ new
operator to instantiate regular C++ unmanaged classes. Once the compiler is able to see the definition of the Tester
class, it will notice this mismatch and generate another error.
Upvotes: 5