Trouble with _TCHAR and using _tcslen

Hey guys, I recently started reading the book Programming Windows Fifth Edition by Charles Petzold and I came about a roadblock. The book mentions a _TCHAR type that I could use for either Unicode or ASCII support depending on whether or not _UNICODE is defined. It also mentions that _TCHAR comes with its own functions. The one I'm trying to use is _tcslen().

The problem is, every time I try using _tcslen() I get an error saying _tcslen was not declared in this scope.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <windows.h>
#include <string.h>
#define _UNICODE
#define UNICODE

int main(){

 _TCHAR x = 'a';
 int tester = 0;

 tester = tcslen(x);


return 0;
}


I'm currently using CodeBlocks as my IDE.
Last edited on
_UNICODE and UNICODE must be defined before including any Windows header. You would normally define these in your project settings, not in any source or header file.
Last edited on
Thanks for the quick reply LB! So I just defined both in my project settings (I'm using CodeBlocks) It was under Project > Build Options > Define. I still get the same Error. The compiler doesn't seem to understand what _tcslen() is, even though I was able to find reference for it on countless MSDB pages. I find this strange because the compiler has no problem with _TCHAR.
Last edited on
I didn't realize you said you were using CodeBlocks - you're probably using GCC or MinGW which doesn't have full proper Windows support. If you want to do Windows development you should just install Visual Studio 2015 - it's free and will save you many headaches.
If you're just going to #define UNICODE (which is probably for the best) then there's no point in using _tcslen(). Just use wcslen().
#include <tchar.h> (It is part of MinGW.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// comment out the next two lines to switch to narrow characters
#define _UNICODE
#define UNICODE

#include <windows.h>
#include <string.h>
#include <tchar.h> 

int main() {

    TCHAR tstr[] = TEXT( "abcdef" ) ; // note TEXT()

    const unsigned int len = _tcslen(tstr) ;
    const unsigned int sz = sizeof(tstr) / sizeof( tstr[0] ) ; // note: divide by sizeof(TCHAR)

    _tprintf( TEXT( "tstr == %s  length: %u  size: %u\n" ), tstr, len, sz );

    TCHAR c = TEXT('!') ;
    tstr[2] = c ;
    _tprintf( TEXT( "tstr == %s  tstr[2] == %c\n"), tstr, tstr[2] ) ;
}
@JLBorges Thanks a lot mate! Including <tchar.h> made the program run. Also thanks for writing out that piece of code, it definitely helped me understand how TCHAR and _tcslen works much better.
Topic archived. No new replies allowed.