error LNK2019: unresolved external symbol (small library) - c++-cli

I've created a small CLR library (MyClient) in VS2005 to integrate threading into an existing C++ application (also written in VS2005). When I build the project get these errors:
1>PSR_CRSDlg.obj : error LNK2019: unresolved external symbol "public: static void __cdecl MyClient::StartClientThread(void)" (?StartClientThread#MyClient##SAXXZ) referenced in function "public: void __thiscall CPSR_CRSDlg::OnBnClickedInit2(void)" (?OnBnClickedInit2#CPSR_CRSDlg##QAEXXZ)
1>PSR_CRSDlg.obj : error LNK2019: unresolved external symbol "public: static void __cdecl MyClient::SendJointValues(double *)" (?SendJointValues#MyClient##SAXPAN#Z) referenced in function "public: void __thiscall CPSR_CRSDlg::OnTimer(unsigned int)" (?OnTimer#CPSR_CRSDlg##QAEXI#Z)
1>PSR_CRSDlg.obj : error LNK2019: unresolved external symbol "public: static void __cdecl MyClient::StopConnection(void)" (?StopConnection#MyClient##SAXXZ) referenced in function "public: void __thiscall CPSR_CRSDlg::OnBnClickedMovepenall(void)" (?OnBnClickedMovepenall#CPSR_CRSDlg##QAEXXZ)
1>D:\Desktop\PSR\Software\Source - June 21\PSR_CRS_SVN - Copy (2)\Debug\PSR_CRS.exe : fatal error LNK1120: 3 unresolved externals
I'm new a bit new to C++ and OOP but have been doing it continuously for the past few weeks. This is my .h file:
using namespace std;
class MyClient
{
public:
static char* createMsg(string s);
static char* parseJSON(double j1, double j2, double j3, double j4, double j5, double j6);
static void StartConnection();
static void StartClientThread();
static void StopConnection();
static void SendJointValues(double *joints);
};
My .cpp file just has the functions instantiated as char* MyClient::createMsg(string s), etc, so I don't think that is the problem. I've also gone through most of the links here and searched a lot to make sure my libraries were all there, no circular lib dependency, library order, etc. Out of the 3 projects in my whole solution, 2 use "No Common Language Runtime support" but my client library uses "Common Language Runtime Support", this is the one difference between the libraries.
Does anyone have thoughts on why these errors are occurring?
Full Client Library:
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include "stdafx.h"
#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <iostream>
#include <typeinfo>
#include <sstream>
#include "Client.h"
using namespace std;
using namespace System;
using namespace System::Threading;
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 4096
#define DEFAULT_PORT "9001"
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
SOCKET ConnectSocket;
char* MyClient::createMsg(string s) {
char *a = new char[s.size() + 1];
a[s.size()] = 0;
memcpy(a, s.c_str(), s.size());
return a;
}
char* MyClient::parseJSON(double j1, double j2, double j3, double j4, double j5, double j6)
{
ostringstream oss;
oss << j1 << ',' << j2 << ',' << j3 << ',' << j4 << ',' << j5 << ',' << j6;
string joints = oss.str();
return createMsg(joints);
}
void MyClient::StartConnection()
{
//printf("Connection Starting... \n");
WSADATA wsaData;
ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
int argc = 2;
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", "client");
return;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
//iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
iResult = getaddrinfo("localhost", DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return;
}
return;
}
void MyClient::StopConnection(){
closesocket(ConnectSocket);
WSACleanup();
return;
}
void MyClient::SendJointValues(double *joints){
char *j;
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
j = parseJSON(joints[0],joints[1],joints[2],joints[3], \
joints[4],joints[5]);
int x = send(ConnectSocket, j, strlen(j), 0);
//iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
}
void MyClient::StartClientThread()
{
Thread^ cln;
ThreadStart ^ClientThread = gcnew ThreadStart(&MyClient::StartConnection);
cln = gcnew Thread(ClientThread);
cln->IsBackground = true;
cln->Start();
}
Edit: These errors did not occur when I created a dummy application when the same settings as the application I am trying to integrate with right now, which is why I'm not sure what has changed or how to resolve the errors.

I think perhaps you're including the header file from the library in your EXE.
When you write a library in C++/CLI, it uses the .Net mechanisms for exported classes. You don't need a header file to declare the class, the .Net metadata takes care of that.
Just make sure that your EXE has a the library added as a .Net reference, and just go ahead and use the library class.

So I'm not sure what the exact cause of this specific error was, but overall I found out that I was having a lot of trouble due to the original application using the /MTd runtime library and my new library using /MD

Related

Simple parsing to a tuple fails

Why does this not compile? The marked line gives me: "static assertion failed: The parser expects tuple-like attribute type". I would think that an std::tuple were the essence of "tuple-like"?
#include <string>
#include <tuple>
#include <boost/spirit/home/x3.hpp>
void parseInteger(std::string input) {
namespace x3 = boost::spirit::x3;
auto iter = input.begin();
auto end_iter = input.end();
int result;
x3::parse(iter, end_iter, x3::int_, result);
}
void parseIntegerAndDouble(std::string input) {
namespace x3 = boost::spirit::x3;
auto iter = input.begin();
auto end_iter = input.end();
std::tuple<int, double> result;
x3::parse(iter, end_iter, x3::int_ >> ' ' >> x3::double_, result); //Compile error!
}
int main(int, char **)
{
parseInteger("567");
parseIntegerAndDouble("321 3.1412");
return 0;
}
The trick is to include two additional header files:
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/include/std_tuple.hpp>
This is a bit more magical than I like, but I've got a feeling I really don't want to know how this works!

read multiple files with quite similar names c++

I am reading a file from current directory
ifstream myfile;
myfile.open("version1.1.hex");
Now a situation is arising that if user updates version then there will be version1.2.hex or version1.3.hex ..so on in the current directory, but one file at a time will be present. I want to write a code now which will cater this future need of reading different file.
I'm writing this code in C++/CLI.
Since file listings are a bit environment-dependant I am not sure if this is helpful to you,
but here is an example how to achieve your goal under the mircosoft regime.
What is needed is the FindFirstFile / FindNextFile calls which query all files matching the fileSearchKey. Then you can use the cFileName part of WIN32_FIND_DATAA as parameter to your open command
string fileSearchKey = "version*";
WIN32_FIND_DATAA fd;
bool bFirstRun = true;
bool bFinishedRun = false;
HANDLE h = INVALID_HANDLE_VALUE;
while (!bFinishedRun)
{
if (bFirstRun)
{
h = FindFirstFileA(fileSearchKey.c_str(), &fd);
bFirstRun = false;
} else
{
if (FindNextFileA(h, &fd) != FALSE)
{
// Abort with error because it has more than one file or decide for the most recent version
} else
{
bFinishedRun = true;
}
}
}
// Load file
ifstream myfile;
myfile.open(fd.cFileName);
This code will look in the directory and take the first file, then quit.
WARNING : this will work only on linux
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <cstring>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace std;
int main ()
{
char n[20];
unsigned char isFolder = 0x4;
unsigned char isFile = 0x8;
DIR *dir;
struct dirent *ent;
dir = opendir ("./");
if (dir != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
//folder sign
if(ent->d_type != isFolder && string(ent->d_name).find("version") != string::npos)
{
cout <<ent->d_name <<"\n";
// Your code
break;
}
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return 0;
}
cout << "=========" << endl;
}
In C++/CLI you should use the .net framework libraries for this. For instance you can use Directory::GetFiles.
using namespace System;
using namespace System::IO;
int main(array<System::String ^> ^args)
{
array<String^>^dirs = Directory::GetFiles(".", "version1.*.hex");
Collections::IEnumerator^ myEnum = dirs->GetEnumerator();
while (myEnum->MoveNext())
{
Console::WriteLine(myEnum->Current);
}
return 0;
}

Is it possible to get list of files in directory using apache portable runtime?

I need to get list of files in directory using APR. How can I do it?
I was looking for answer in documentation, but found nothing.
Thanks!
The function you want is apr_dir_open. I found the header files to be the best documentation for APR
http://apr.apache.org/docs/apr/1.4/group_apr_dir.html
Here is an example for reading "." and reporting errors if any were encountered
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <apr.h>
#include <apr_errno.h>
#include <apr_pools.h>
#include <apr_file_info.h>
static void apr_fatal(apr_status_t rv);
int main(void)
{
apr_pool_t *pool;
apr_status_t rv;
// Initialize APR and pool
apr_initialize();
if ((rv = apr_pool_create(&pool, NULL)) != APR_SUCCESS) {
apr_fatal(rv);
}
// Open the directory
apr_dir_t *dir;
if ((rv = apr_dir_open(&dir, ".", pool)) != APR_SUCCESS) {
apr_fatal(rv);
}
// Read the directory
apr_finfo_t finfo;
apr_int32_t wanted = APR_FINFO_NAME | APR_FINFO_SIZE;
while ((rv = apr_dir_read(&finfo, wanted, dir)) == APR_SUCCESS) {
printf("%s\t%10"PRIu64"\n", finfo.name, (uint64_t)finfo.size);
}
if (!APR_STATUS_IS_ENOENT(rv)) {
apr_fatal(rv);
}
// Clean up
apr_dir_close(dir);
apr_pool_destroy(pool);
apr_terminate();
return 0;
}
static void apr_fatal(apr_status_t rv)
{
const int bufsize = 1000;
char buf[bufsize+1];
printf("APR Error %d: %s\n", rv, apr_strerror(rv, buf, bufsize));
exit(1);
}

boost multi_index_container serialization

I am trying to use the boost::multi_index_container with the boost::serialization. However when I use Pointer to objects as elements and a non_unique order, I get a memory access violation loading the serialized container. I find it interesting that the error doesn't occur for unique ordering or using objects instead of pointers as container elements.
Can somebody tell me if there is a problem with my code or if this is a bug in the boost library?
Here is a minimal example that produces the described error:
#include <boost/multi_index_container.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/set.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <fstream>
using namespace std;
using namespace boost::multi_index;
struct element {
friend class boost::serialization::access;
std::string member1;
element( int num ) { member1 = boost::lexical_cast<string>( num ); }
element() {}
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & member1;
}
};
int main( int argc, const char *argv[] )
{
typedef multi_index_container<element *, indexed_by<ordered_non_unique<member<element, std::string, &element::member1>>>> TestSet;
TestSet myset;
srand( time (NULL ));
for (int i = 0; i < 20; i++) {
myset.insert(new element(rand()));
}
// Write set
ofstream os("test.bin");
boost::archive::binary_oarchive boa(os);
boa << myset;
os.close();
// Read set
TestSet newset;
ifstream is("test.bin");
boost::archive::binary_iarchive bia(is);
bia >> newset;
return 0;
}
ofstream os("test.bin"); should be:
ofstream os("test.bin", ios::binary);
Also:
ifstream is("test.bin"); should be: ifstream is("test.bin", ios::binary);

simple linux device driver open call crash

I am trying to learn how to write a device driver in linux, following some reference from google and ldd3. i am able to insert the module below but when i tried to open the device in an application the kernel crashed.
The code and build steps followed as below :
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
#include <linux/init.h> /* Needed for the macros */
#include <linux/ioport.h>
#include <asm/io.h>
#include <linux/interrupt.h>
#include <linux/sched.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/param.h>
#include <linux/fs.h>
/* =============== Constant Definitions ============ */
#define SERIAL_IRQ 4
/* =============== Variable Definitions ============ */
static int SER_MAJOR = 0;
int ser_open(struct inode *inode, struct file *filp);
int ser_release(struct inode *inode, struct file *filp);
irqreturn_t my_ser_dev_isr(int irq,void *ser_data,struct pt_regs * pt_reg_var)
{
printk("\n\n ------- INTR raised -----------\n\n");
return 0;
}
int ser_open(struct inode *inode, struct file *filp)
{
if(request_irq(SERIAL_IRQ,&my_ser_dev_isr,1,"my_ser_dev_intr",NULL))
{
printk("\n interrupt req failed\n");
}
else
{
enable_irq(SERIAL_IRQ);
printk("\n!!!! ..obtained the requested interrupt and enabled\n");
}
}
int ser_release(struct inode *inode, struct file *filp)
{
disable_irq(SERIAL_IRQ);
free_irq(SERIAL_IRQ,NULL) ;
}
static struct file_operations ser_fops = {
open: ser_open,
release: ser_release
};
void *p = NULL;
irqreturn_t my_ser_dev_isr (int, void *, struct pt_regs *);
static int __init hello_start(void)
{
int ret_val=-1;
int result;
printk(KERN_INFO "Loading hello module...\n");
printk(KERN_INFO "Hello world\n");
result = register_chrdev(SER_MAJOR,"SER_DEV",&ser_fops);
if(result < 0)
{
printk(KERN_WARNING"Can't get major %d\n",SER_MAJOR);
return result;
}
if(SER_MAJOR == 0)
{
SER_MAJOR = result;
printk("SER DEV Major Number : %d",SER_MAJOR );
}
return 0;
}
static void __exit hello_end(void)
{
// free_irq(SERIAL_IRQ,NULL);
//release_region(0x0031,1);
printk(KERN_INFO "Goodbye Mr.\n");
}
module_init(hello_start);
module_exit(hello_end);
Makefile for module :
obj-m := hello.o
default:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
The application used for accesing is as follows :
#include <stdio.h> /* test.c */
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
static int dev;
int main(void)
{
char buff[40];
dev = open("/dev/my_ser_dev",O_RDONLY);
if(dev < 0)
{
printf( "Device Open ERROR!\n");
exit(1);
}
printf("Please push the GPIO_16 port!\n");
//read(dev,buff,40);
// scanf("%s",buff);
printf("%s\n",buff);
close(dev);
return 0;
}
insmod gave
[ 3837.312140] Loading hello module...
[ 3837.312147] Hello world
[ 3837.312218] SER DEV Major Number : 251
Then I created the special file using mknod /dev/my_ser_dev c 251 0
Executing the application caused kernel crash. I am using UBUNTU 3.2.0-23-generic-pae.
The function you are registering as your IRQ handler has the wrong prototype - it should be like
irqreturn_t irq_handler(int, void *);
Maybe you are referring to old documentation.