Thursday, November 06, 2008

c++ - A ready reckoner

1)typedef syntax for function name:
Usage : typedef return-type (classname::*fnname)(argument)
2)Operators that cannot be used for overloading
:: . .* .->
Scope resolution member selection member selection through pointer to function
3)int A::a=0; initializing static variables where a is a static int in class A
4)explicit constructors dissallow use of automatically generated functions
explicit stack(int a)
{

}
main()
{
stack a=10;//will not call statck(int a ) since explicit is specified
}

5.Const members can be initialized only usuing initialization list
stack():a(10) if a is of type const int a;
trick:
stack{
enum{a=10};// initializes a to 10
}

6: const * char a=5; constant pointer
const char * a=5;pointer to a constant
7.Dynamic cast converts base class object to derived class object
8.Virtual destructor is needed in Base class when Base class ptr points to derived object
otherwise derived destructor will not get called
9.Base ptr can be assigned to derived but not vice versa
10.operator new can be overloaded
11.To convert an object of type S to an int then we need to define a conversion operator()
operator int()
{
return this->i; //where i is an int i member of class S
}
void main()
{
int i;
S s;
i=s;//calls operator int
}
12) Making a privately inherited member function public
say fun is public in base class and we inherit this by private inheritance
then declare base::fun(no arguments or return values) in public: of derived
fun will be accesible to objects of derived class

13) say top is a global var and top is also a variable inside a class then
::top inside the class refers to the global variable
14)protected member cannot be accessed from main
15)derived():base() is the same as derived() cause anyway derived object will first call base class constructor
16)class D:public B1,public B2
construction:B1,B2,D
destrcution:D,B2,B1
17)Friends of a base class are not inherited by any classes derived from that base class
18)The name of a friend function or class first introduced in a friend declaration is not in the scope of the class granting friendship (also called the enclosing class) and is not a member of the class granting friendship
19)
using directive - using namespace std //provides access to all members
using declarative-using A::x
explicit A::x
20)
When operator() is overloaded...The function call a('z') is interpreted as a.operator()('z').
similarly A(obj_B) will be obj_B.operator A()
21)A pseudo destructor has no effect at all
22)Malloc fails with std::bad_alloc
23)Virtual function mechanism does not work within the constructor
i.e when a derived object is created first base class constructor is called and if a virtual fn is called from within
the base class constructor it will still call only the base class version since the derived object is still not constructed
24)Operator new(size_t sz)
X * ptr=new X; is equivalent to new(Size(X))
The statement delete ptr calls X::operator delete(void*) delete when overloaded accepts a void pointer
25)const data are initialized in the initialization list....there is no const class
26)copy constructor gets called in call and retun by value
26a) When an object is passed to a function,the constructor does not get called even though a local temp object is created
27)class A
{
void display const();
};
defn: A::display()const
{}
28)
A copy constructor of a class A is a non-template constructor in which the first parameter is of type A&, const A&, volatile A&, or const volatile A&, and the rest of its parameters (if there are any) have default values.

29)

template syntax: template class mycontainer { ... };
specialization specialization syntax:template <> class mycontainer { ... };

30)

template
T mypair::getmax ()
Confused by so many T's? There are three T's in this declaration: The first one is the template parameter. The second T refers to the type returned by the function. And the third T (the one between angle brackets) is also a requirement: It specifies that this function's template parameter is also the class template parameter


31)
A function try block on main() does not catch exceptions thrown in destructors of objects
with i)static storage duration, or ii)constructors of namespace scope objects
i) ex.
void main()
{
A a;
static B b;
}
if exception is thrown in Destructors of A and B only A's will be called.B is staic so will not be called
ii)
namespace N {
class C {
public:
C() {
cout << "In C()" << pilocal =" const_cast">(const_int_arg);
*piLocal = iVal; //able change value of const int
piLocal is int* type.
static_cast:any standard conversion
reinterpret_cast:converison to any other type
int i;
char *cpPtr = "Hello World";
i = reinterpret_cast (cpPtr);
37)
Sample s;
s=i;(overload operator() to return int)
s=s+10(overload +operator accepting sample parameter and provide one argument constructor)
38)
const function prevents the modification of the data members of the class within it
39)
conversion operators have the same name and return tyoe of the object to whic they are converted to
ex.operator int(){
return this->i;}
operator circle(){ //inside operator circle() is in shape class
return circle(data);} circle c;shape s;
c=s;//calls conversion operator
40)
function pointer with typedef
int fun(int,int);
typedef int (*pftr)(int,int);
void main()
{
pftr pf=fun;
}
function pointer without typedef//not that impor
void main()
{
int(*pftr)(int,int);//prototype
*pftr=fun
}
(*pftr)(10,2)

41)If a pure virtual fn in Base is not implementedin Derived,the Derived class also becomes abstract and we cannot create objects of the Derived class also
42)Unexpected throws bad_exception if the fn calling unexpected include std::bad_exception throw in the throw list
If not included Unexpectd calls its default i.e terminate
43)sequence
try=>throw=>catch=>unexpected=>terminate=>abort
..................... (MyUnexpected)=>(Myterminate)

44)Dynamic cast:
conversion between same types,conversion from base to derived if base*ptr points to derived
const_cast convert from const to ordinary
static_cast standard casting i.e int to double etc...
reinterpret cast -fully different int to char etc...
45)
The STL provides 11 containers, divided into four categories.
The sequential containers include the- vector (dynamic array), list, and deque.
The container adapters -queue, priority_queue, and stack.
The associative containers-map, multimap, set, and multiset.
The final container, the bitset, is in a class of its own.
46)

STL algorithms:
Utility-min,max,swap
Non-Modifying-find,find_if
Numeric:accumulate()
Comparison:equal,mismatch,lexicographic_compare()
operational:for_each()

47)const objects can call only const member function
48)In the diamond problem,the most derived i.e the class lowest in the list should initialize the VB class.


Extra:

1)Call to pure virtual function directly will result in runtime exception
class test
{
A()
{
fun();
}
virtual void fun()=0;
};
2)In the diamond problem the Virtual Base class value will be the one assigned by the constructor at the bottom of the diamond.
3)Base class pointers cannot be passed to functions which take Derived class pointer.

4)In templates for the ones with non type arguments like template class test
the following will work
const int t;
test since t is const int if it is int t then it will give compilation error.const can be signed or unsigned
5)
Note that in const pointers, "const" always comes after the "*". For example:

int *const p1 = q; // constant pointer to int variable
int const* p2 = q; // pointer to constant int
const int* p3 = q; // pointer to constant int
6)int can be converted to signed char,unsigned char or char
fn('A') will call int if char not available...it will not call short fn(0) will call fn(int)
7)Fn<>(2,3) will also call Fn(T t,U u)
8)An ordinary non template function is always given priority over the template instantiation function
so fin(2,3) will call Fn(Tt,Uu) over Fn(in,int)...no compilation eror
9)bitset::count gives no.of set bits
10)In function overloading ,if there is polymorphism(base ptr pointing to derived) then the matching is as follows
i)If base version has stronger match(send char and if base has double and derived has int...double>int match to char)
then base version gets called
ii)if base and derived have equal strngth then base version is called
11)ordinary fn always given priority over similar overloaded template ones
12) class X
{
int f(X&){}
}
main(){ f(10);//error will call only if f takes const X& or X and not X&}
13) w.r.to 12
int &x=1;//error
const int &x=1;//correct
14)return by reference is ok as long as the refernce does not point to a local object
15)Bufferis same as Buffer
int& f(){int a;return a;//problem)
16)A pure virtual fn should be overridden by derived class and till it is overridden the intermediate derived calsses are all abstarct classes i.e we cannot create objects of those classes(even if other functions are there)
17)In templates,
i)first instatiation is done,if exact match is there with a user defined specialisation(here int)then int is called
ii)If there is no exact match then it calls the template instantiation(even though 'a',b' can be converted to int,still
template version is called since instatiation gives char,char
Hint:do instantiation and treat is as if that function is physically there and then apply operator overloding rules.

Sunday, April 16, 2006

Closing the dialog smoothly(fade out)

http://www.codeguru.com/cpp/w-d/dislog/animation/article.php/c5063/

I "found" how to close a dialog box smoothly that is fade away.....

code snippets:

#include //for User32.dll
HMODULE hUserDll;
#define WS_EX_LAYERED 0x00080000
#define LWA_ALPHA 0x00000002

hUserDll = ::LoadLibrary(_T("USER32.dll"));
//Change style to layered window style...
::SetWindowLong(m_hWnd, GWL_EXSTYLE, ::GetWindowLong(m_hWnd, GWL_EXSTYLE) | WS_EX_LAYERED );
SetTransparent(m_hWnd, 0, 255 * 100/100 , LWA_ALPHA );

//The above will set the window to a layered style and the initial transparency value is set

void CMyDialog::SetTransparent(HWND hWnd, COLORREF crKey,
BYTE bAlpha, DWORD dwFlags)
{
BOOL bRet = TRUE;
typedef BOOL (WINAPI* lpfnSetTransparent)(HWND hWnd,
COLORREF crKey,
BYTE bAlpha,
DWORD dwFlags);

// Check that "USER32.dll" library has been
// loaded successfully...
if (hUserDll )
{
lpfnSetTransparent pFnSetTransparent = NULL;
pFnSetTransparent =
(lpfnSetTransparent)GetProcAddress(hUserDll,
"SetLayeredWindowAttributes");

if (pFnSetTransparent )
bRet = pFnSetTransparent(hWnd, crKey, bAlpha, dwFlags);
else
bRet = FALSE;
} // if( m_hUserDll )

return bRet;
} // End of SetTransparent function

//The above will set the transparency of the window(here dialog)
void CMyDialog::CloseSmoothly()
{
// Increase transparency one percent each time...
for(int nPercent=100; nPercent >= 0 ;nPercent--)
SetTransparent( m_hWnd, 0, 255 * nPercent/100, LWA_ALPHA);
if( hUserDll )
FreeLibrary(hUserDll);
}

Thursday, April 06, 2006

Creating a Tabbed Property Sheet with 2 embedded Property pages:

//This is a simple SDK approach u can also use CPropertypage

Creating a Tabbed Property Sheet with 2 embedded Property pages:

Description:
============
PROPSHEETHEADER m_PropSheet;
PROPSHEETPAGE m_psp[2];

LRESULT CALLBACK SheetProc(HWND, UINT, WPARAM, LPARAM);
//callback for Property sheet
LRESULT CALLBACK Page1DlgProc(HWND, UINT, WPARAM, LPARAM);
//callback for Property Page 1
LRESULT CALLBACK Page2DlgProc(HWND, UINT, WPARAM, LPARAM);
//callback for Property Page 2

memset(m_psp, 0, sizeof(m_psp));
memset(&m_PropSheet, 0, sizeof(m_PropSheet));

//allocate memory for property pages
//initialize property page structure
m_psp[0].dwSize = sizeof(PROPSHEETPAGE);
m_psp[0].dwFlags = PSP_DEFAULT|PSP_USETITLE;
m_psp[0].pszTemplate = (LPCSTR)IDD_PAGE1;
//IDD_PAGE1 is the dialog box for page1,create it in the resource
m_psp[0].pszTitle = "Page 1";
m_psp[0].pfnDlgProc = (DLGPROC)Page1DlgProc;
//Page1DlgProc is the callback procedure for Page1 dialog

//do the same for page 2

m_psp[1].dwSize = sizeof(PROPSHEETPAGE);
m_psp[1].dwFlags = PSP_USETITLE;
m_psp[1].pszTemplate = (LPCSTR)IDD_PAGE2;
m_psp[1].pszTitle = "Page 2";
m_psp[1].pfnDlgProc = (DLGPROC)Page2DlgProc;

//Initialize property sheet structure
m_PropSheet.dwSize = sizeof(PROPSHEETHEADER);
m_PropSheet.dwFlags = PSH_PROPSHEETPAGE | PSH_USECALLBACK;
m_PropSheet.pszCaption = (LPSTR) "Property Sheet";
m_PropSheet.nPages = 2;
m_PropSheet.nStartPage = 0;
m_PropSheet.ppsp = (LPCPROPSHEETPAGE)m_psp;
m_PropSheet.pfnCallback = (PFNPROPSHEETCALLBACK) SheetProc;

Call this code where required say froma dialog or from a window….pass the appropriate handle.
m_PropSheet.hwndParent = CPropSheetDlg::m_hWnd;
PropertySheet(&m_PropSheet);//invokes the property sheet with 2 pages

Source code:

I have popped the property sheet from a Dialog PropsheetDialog on click of "Prop "button

Create an MFC dialog application called PropSheetDlg and add the following code in PropSheetDlg.cpp
This is the propsheetdlg.cpp code

// PropSheetDlg.cpp : implementation file
//

#include "stdafx.h"
#include "PropSheet.h"
#include "PropSheetDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
CAboutDlg();

// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA

// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL

// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CPropSheetDlg dialog

CPropSheetDlg::CPropSheetDlg(CWnd* pParent /*=NULL*/)
: CDialog(CPropSheetDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CPropSheetDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CPropSheetDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CPropSheetDlg)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CPropSheetDlg, CDialog)
//{{AFX_MSG_MAP(CPropSheetDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_PROP, OnProp)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CPropSheetDlg message handlers
PROPSHEETHEADER m_PropSheet;
PROPSHEETPAGE m_psp[2];
LOGFONT m_lfont;

LRESULT CALLBACK SheetProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK Page1DlgProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK Page2DlgProc(HWND, UINT, WPARAM, LPARAM);


BOOL CPropSheetDlg::OnInitDialog()
{
CDialog::OnInitDialog();

// Add "About..." menu item to system menu.

// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);

CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}

// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon

// TODO: Add extra initialization here

memset(m_psp, 0, sizeof(m_psp));
memset(&m_PropSheet, 0, sizeof(m_PropSheet));

m_psp[0].dwSize = sizeof(PROPSHEETPAGE);
m_psp[0].dwFlags = PSP_DEFAULT|PSP_USETITLE;
//m_psp[0].hInstance = NULL;
m_psp[0].pszTemplate = (LPCSTR)IDD_PAGE1;
m_psp[0].pszTitle = "Page 1";
m_psp[0].pfnDlgProc = (DLGPROC)Page1DlgProc;
//m_psp[0].pfnCallback = (LPFNPSPCALLBACK) Page1Proc;

m_psp[1].dwSize = sizeof(PROPSHEETPAGE);
m_psp[1].dwFlags = PSP_USETITLE;
//m_psp[1].dwFlags = PSP_USETITLE | PSP_USECALLBACK;
//m_psp[1].dwFlags = PSP_USECALLBACK;
//m_psp[1].hInstance = hInstance;
m_psp[1].pszTemplate = (LPCSTR)IDD_PAGE2;
m_psp[1].pszTitle = "Page 2";
m_psp[1].pfnDlgProc = (DLGPROC)Page2DlgProc;
//m_psp[1].pfnCallback = (LPFNPSPCALLBACK) Page2Proc;

m_PropSheet.dwSize = sizeof(PROPSHEETHEADER);
m_PropSheet.dwFlags = PSH_PROPSHEETPAGE | PSH_USECALLBACK;
//m_PropSheet.dwFlags = PSH_PROPSHEETPAGE | PSH_USECALLBACK | PSH_MODELESS;
// m_PropSheet.hInstance = hInstance;
m_PropSheet.pszCaption = (LPSTR) "Property Sheet";
m_PropSheet.nPages = 2;
m_PropSheet.nStartPage = 0;
m_PropSheet.ppsp = (LPCPROPSHEETPAGE)m_psp;
m_PropSheet.pfnCallback = (PFNPROPSHEETCALLBACK) SheetProc;

return TRUE; // return TRUE unless you set the focus to a control
}

void CPropSheetDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}

// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.

void CPropSheetDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting

SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;

// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}

// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CPropSheetDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}

LRESULT CALLBACK SheetProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{


// set a bold font to the tabs
m_lfont.lfHeight = 8;
m_lfont.lfWeight = FW_NORMAL;
m_lfont.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
strcpy(m_lfont.lfFaceName, _T("Arial"));
HWND hTabCtrl = PropSheet_GetTabControl(hDlg);
SendMessage(hTabCtrl, WM_SETFONT, (WPARAM)&m_lfont, 0);
switch( message )
{
case WM_INITDIALOG:
return TRUE;
}
return FALSE;
}

// Dialog proc for page 1
LRESULT CALLBACK Page1DlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{

switch (message)
{
/*case WM_INITDIALOG:
{
//SetWindowText(GetDlgItem(hDlg, IDC_EDITX), "A * cos(u) * cos(v)");
//SetWindowText(GetDlgItem(hDlg, IDC_EDITY), "A * sin(u) * cos(v)");
// SetWindowText(GetDlgItem(hDlg, IDC_EDITZ), "A * sin(v)");
return TRUE;
}
case WM_COMMAND:
//if the textboxes are changed
if (HIWORD(wParam) == EN_CHANGE) {
SendMessage(GetParent(hDlg), PSM_CHANGED, (WPARAM)hDlg, 0);
}
break;
case WM_NOTIFY:
switch (((NMHDR FAR *) lParam)->code) {
case PSN_APPLY:
//user clicked APPLY
MessageBox(hDlg, "Apply", "Page1", 0);
break;
case PSN_KILLACTIVE:
//user clicked OK or selected another page
MessageBox(hDlg, "OK", "Page1", 0);
break;
}*/
}
return FALSE;

}

LRESULT CALLBACK Page2DlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
/*case WM_INITDIALOG:
return TRUE;
case WM_NOTIFY:
// switch (((NMHDR FAR *) lParam)->code) {
//case PSN_APPLY:
//user clicked APPLY
// MessageBox(hDlg, "Apply", "Page2", 0);
//break;
case PSN_KILLACTIVE:
//user clicked OK or selected another page
// MessageBox(hDlg, "OK", "Page2", 0);
// break;
}*/
}
return FALSE;

}// Page2DlgProc(HWND, UINT WPARAM, LPARAM)


void CPropSheetDlg::OnProp()
{
// TODO: Add your control notification handler code here
m_PropSheet.hwndParent = CPropSheetDlg::m_hWnd;
PropertySheet(&m_PropSheet);


}

Tuesday, March 14, 2006

My Own Edit Box(VC++)

We will see here how to create an Edit Box which say disallows CUT+COPY+PASTE

The normal class CEdit does not have API corresponding to this so this essentially requires subclassing

Say we have a Dialog CNoCutCopyPasteDialog

and we have a control IDC_EDIT1 which is an EDIT BOX....

We will have to route all messages coming to the IDC_EDIT1 control to our own class so that we can trap them in the way we want.

This is simple enough.
In DO Data Exchange of the CNoCutCopyPasteDialog
add
DDX_Control(pDX, IDC_EDIT1, m_Edit1);

What this effectively does is routes all messages coming to IDC_EDIT1 to the object m_Edit1.

Create a new class CMyEdit derived from CEdit
Declare CMyEdit m_Edit1 in the CNoCutCopyPasteDialog

In the CMyEdit class add the message handler

LRESULT CMyEdit::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
// TODO: Add your specialized code here and/or call the base class

if((WM_PASTE==message)||
(WM_COPY==message)||
(WM_COPY==message))
{
MessageBox("U cannot paste here",NULL,MB_OK);
return 0L;
}
else
{
return CEdit::WindowProc(message,wParam,lParam);
}

}

This means that all Edit box messages are routed to CMyEdit class and CUT,COPY,PASTE messages are handled all other messages are returned to the parent CEdit class

Saturday, December 03, 2005

"Pointers" to ponder

I think the word "pointer" is big in the heads of all softies...yep.But I guess there is an easy way to understand them...trick is to think them as mere numbers.
So if that unique number is getting changed unnecessarily...we get a crash....similarly if that number is garbage we get a crash.

ex.CPointerExample *cpe;
cpe->method();//crash cpe is not yet a number i.e no value assigned
most cross referencing crashes can be avoided if we think of a pointer as numbers being passed around so if that number is being changed then there is a crash....

example:

Module 1:
CPointerExample *cpe;
cpe=new CPointerExample();
cpe->SomeUniqueMethod();

Module....n
has to use cpe of Module1

but here does CPointerExample *cpe=new CPointerExample();
cpe->SomeUniqueMethod();

we have a crash because cpe has changed....

Saturday, September 24, 2005

Importing dll's into vc++(error LNK2001 Undefined External Symbol)

The best part of this problem is I did not know the error LNK2001 Undefined externals was problem with importing Dll's.So this title is a special one.
Yes Identifying the problem solves most of the problem thaks to Google!!!
Thanks to the post
http://www.codeproject.com/dll/XDllPt1.asp

I got this linkage error LNK2001 when I was trying to link a library to be used in my code.Most of it were API calls to that library.I tried to include in
Tools->Options->Directories
and had included all necessary libs,includes and executables...but it was still
Om 'Bug'aaya namaha

I was sitting on this problem and well out of the blue the word Dll crept into me...how
no idea....God must have sympathised.So just searched for importing dlls into vc++
and Bingo I came across this post.

So if u want to link Dll's do following

i)Make sure all includes are correct i.e
Go to Tools->Options->Directories
Under Include Files give include path..something like e:\MyDir\Include Under Library Files give include path..something like e:\MyDir\bin
Under Executables give include path..something like e:\MyDir\bin
ii)Go to Project->Settings->Link
Under Object/Library Modules
Enter path of the library like e:\MyDir\bin\My_lib.lib
iii)Go to Project->Settings->c/c++
Category:Preprocessor
Under Additonal Include Directories give path of directory e:\Mydir\bin
where ur Dll,Lib etc are dumped
iv)Copy the .dll file into the Debug folder of ur project

Rebuild All and yep it works