Search code examples
c++visual-studio-2008scopeheader-filespragma

What is the scope of a pragma directive?


What is the scope of a pragma directive? For example, if I say #pragma warning(disable: 4996) in a header file A that is included from a different file B, will that also disable all those warnings inside B? Or should I enable the warning at the end of file A again?


Solution

  • It is till the end of the translation unit. Informally, a TU is the source file with its include files.

    The usual pattern is this:

    #pragma warning (push) //save
    #pragma warning (disable: xxxx)
    #pragma warning (disable: yyyy)
    ...
    
    //code
    
    #pragma warning (pop) //restore prev settings
    

    for example

    //A.h
    #pragma once
    #pragma warning (disable: 1234)
    #include "b.h"
    
    //b.h
    #pragma once
    //when included after a.h 1234 will be disabled
    
    //c.cpp
    #include "a.h" //warnings 1234 from b.h is disabled
    
    //d.cpp
    #include "b.h" //warnings 1234 from b.h are not disabled
    #include "a.h"