You set the cookie too late. You can use any action before template_include
to set a cookie, after that there is already HTML output, and no further headers can be set.
Example:
add_action( 'template_redirect', function()
{
setcookie( 'test', 1 );
});