• C

strdup question

What header file is strdup located in and do I need to link to any libs in my project to use it?  I am trying to compile someone else's C code that uses the function and I get this error:

Link error:
Undefined symbol: _strdup

This code compiled and linked as a dll before I exported any functions.  After I added __declspec(dllexport) to some of the functions, I started to get this error.  How can I fix this?
Who is Participating?
brettmjohnsonConnect With a Mentor Commented:
strdup() is not in the ANSI C spec, so Microsoft makes it difficult to use
if you specify strict ANSI to the compiler.  If you look in string.h, you will
likely see a block like this:

/* Nonstandard routines */
#ifndef _ANSI_SOURCE
char    *strdup(const char *);

#include <string.h>
thedude112286Author Commented:
To get the code to compile, I had to change calls to strdup into calls to _strdup.  Now it works fine.  Why did this happen?
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

try write a function...

#include <string.h>
char* strdup ( const char *str_in )
int len = strlen( str_in ) + 1;
char *str_cpy = malloc (len);
if (str_dup == NULL) return NULL;
return ((char *) memcpy (str_dup, str_in, len) );
Kent OlsenData Warehouse Architect / DBACommented:
Hi Brett,

That's a good post about the Micro$oft ANSI compliance.  I didn't realize that strdup() isn't ANSI and that Micro$oft treated it this way.

Thanks for the tip!
hey .. "strdup into calls to _strdup."
whats the difference ?
Kent OlsenData Warehouse Architect / DBACommented:

The compiler prepends an underscore ('_') onto function names (actually, any external, I believe) prior to inserting the name into the object file.

When you compile strdup(), the compiler places _strdup into the object file.  The linker then "sees" the name _strdup and links it.

As I recall, this the compiler's way of "separating" local variables from externals.  The names of the "local" variables remain intact and the externals have the underscore prepended.

thanks Kent
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.