Skip to content

PCH source file rebuilt every time when certain filenames are used #2249

Open

Description

@bdbaddog

This issue was originally created at: 2008-11-01 23:58:39.
This issue was reported by: jchristian.

jchristian said at 2008-11-01 23:58:39

Scons Version: Using "vs_revamp" branch build off of the 1.1.0 release. I suspect this problem happens on the official 1.1.0 release, but I haven't checked it.

Compiler: VS2008

Defect Summary: In attempting to use precompiled headers in building a Windows project, I ran into a fairly obscure bug. Apparently, if the filename specified as the source file for the PCH generation begins with the letter 'c' or 'C', the build regenerates the PCH file every time the build is run...even if no files have changed. If I change that filename to begin with another letter, it works. Note that originally my PCH source file was called "CorePCH.cpp". In trying things, I found it could be shortened to just "C.cpp" and produce the problem.

Expected Behavior: On the second build, it should just return with an "up to date" status.

Below is my directory structure and the files needed to reproduce the issue. Note that once you get this all setup, you can make it work successfully by changing the filename C.cpp in the SConscript to just PCH.cpp or XCorePCH.cpp.

Let me know if you have questions.

Directory structure:

project
    |
    +--SConstruct
    |
    +--include
    |    |
    |    +-- core
    |         |
    |         +-- CorePCH.hpp
    |             Hello.hpp
    |
    +-- lib
         |
         +-- core
              |
              +-- CorePCH.cpp
                  Hello.cpp
                  SConscript 

SConscript:

import glob

# get all the build variables we need
Import("env", "buildroot", "project", "mode", "debugcflags", "releasecflags")
staticlibenv = env.Clone()

builddir = buildroot + "/" + project  # holds the build directory for this
project
targetpath = builddir  # holds the path to the executable in the build directory

# append the user's additional compile flags
# assume debugcflags and releasecflags are defined
if mode == "debug":
    staticlibenv.Append(CPPFLAGS=debugcflags)
else:
    staticlibenv.Append(CPPFLAGS=releasecflags)


# get source file list
srclst = map(lambda x: builddir + "/static/" + x, glob.glob("*.cpp"))

# specify the build directory
staticlibenv.BuildDir(builddir + "/static", ".", duplicate=0)

staticlibenv2 = staticlibenv.Clone()
staticlibenv2["PCHSTOP"] = "core/CorePCH.hpp"
# pch.cpp is beside this SConscript
staticlibenv2["PCH"] = staticlibenv2.PCH(builddir + "/static/C.cpp")[0]
print("here 0")
print(staticlibenv2["PCH"])
print("here 1")
additionalcflags = ["-Yl__xge_pch_symbol"]
staticlibenv2.Append(CPPFLAGS=additionalcflags)
staticlib = staticlibenv2.StaticLibrary(targetpath + "/static/core", source=srclst)

SConstruct:

# get the mode flag from the command line
# default to 'release' if the user didn't specify
mode = ARGUMENTS.get("mode", "debug")  # holds current mode
platform = ARGUMENTS.get("platform", "win32")  # holds current platform

# check if the user has been naughty: only 'debug' or 'release' allowed
if not (mode in ["debug", "release"]):
    print("Error: expected 'debug' or 'release', found: " + mymode)
    Exit(1)

# check if the user has been naughty: only 'win32' or 'xbox' allowed
if not (platform in ["win32", "xbox"]):
    print("Error: expected 'win32' or 'release', found: " + platform)
    Exit(1)


# tell the user what we're doing
print("**** Compiling in " + mode + " mode...")

debugcflags = [  # extra compile flags for debug
    "-Od",
    "-MDd",
    "-Ob0",
    "-Z7",
    "-W4",
    "-EHsc",
    "-GR",
    "-D_DEBUG",
    "-DUSE_PCH",
]
releasecflags = [  # extra compile flags for release
    "-O2",
    "-MD",
    "-Ob2",
    "-EHsc",
    "-GR",
    "-DNDEBUG",
    "-DUSE_PCH",
]

env = Environment()

env.Append(CPPPATH=["#include", "#ext/boost-1.34.1"])

if mode == "debug":
    env.Append(LINKFLAGS="/DEBUG")

buildroot = "#build/" + mode  # holds the root of the build directory tree

# make sure the sconscripts can get to the variables
Export("env", "mode", "platform", "debugcflags", "releasecflags")

# put all .sconsign files in one place
env.SConsignFile()

# specify the sconscript for myprogram
project = "lib/core"
SConscript(project + "/SConscript", exports=["buildroot", "project"])

CorePCH.hpp:

#ifndef CORE_PCH_HPP
#define CORE_PCH_HPP
 
#ifdef USE_PCH
#include <string>
#include <iostream>
#include "core/Hello.hpp"
#endif
 
#endif // CORE_PCH_HPP

CorePCH.cpp or C.cpp:

#include "core/CorePCH.hpp"

Hello.hpp:

#ifndef HELLO_HPP
#define HELLO_HPP
 
#ifndef USE_PCH
#include <string>
#endif
 
class Hello
{
    public:
       Hello(const std::string& msg);
       ~Hello();
       void sayIt();
       
   private:
      std::string m_msg; 
};
#endif // HELLO_HPP

Hello.cpp:

#include "core/CorePCH.hpp"
#ifndef USE_PCH
#include "core/Hello.hpp"
#include <iostream>
#endif
 
Hello::Hello(const std::string& msg):m_msg(msg)
{
}
 
Hello::~Hello()
{
}
 
void Hello::sayIt()
{
    std::cout << m_msg << std::endl;
}

jchristian said at 2008-11-02 00:08:53

I made this a P2 because even though it is obscure, it is hella hard to track down what is going on. The workaround is to simply use another filename but this isn't apparent until many hours have been wasted. As well, I suspect the fix will be trivial and from my experience P3 and P4 defects tend to get put off practically forever.

jchristian said at 2008-11-04 00:39:53

Created an attachment (id=531)
Zip file that creates the dir structure described in the defect

jchristian said at 2008-11-04 00:49:32

Upon further investigation I have found that the filenames A.cpp thru H.cpp do not work. I have confirmed that I.cpp thru Q.cpp work. And also X.cpp. Other filenames were not tested because I got tired of doing it. To test a different filename, simply rename C.cpp in the lib/core directory and then update the SConscript file in that same directory to use that filename.

My suspicion is that the dependencies are not being generated or kept because of some defect in parsing or concatenating the filename.

jchristian said at 2008-11-04 00:55:43

Hopefully this can be fixed for 1.2

gregnoel said at 2008-12-04 17:41:09

1.2 is frozen; issues that didn't make it into 1.2 are moved to 1.3.

stevenknight said at 2008-12-06 11:22:53

This issue erroneously had a target milestone put on it right away, so it never got discussed and assigned to someone specific. Consequently, it's been languishing in a 1.[23] + issues@scons bucket that no one actually looks at. Change the target milestone to -unspecified- so we can discuss this at the next Bug Party and get it prioritized appropriately.

gregnoel said at 2008-12-24 06:41:53

Bug party triage. Steven suggests that it might be an interaction with the heuristics for determining the drive letter, but otherwise nobody has a clue. Assign to Steven for research as a penalty for suggesting a possibility.

Next time let us assign the milestone and priority. If it doesn't pass through our process, it'll get lost as this one did.

jchristian said at 2008-12-24 12:26:00

Sorry about that, I'll do that in the future. This was my first issue submitted and I wasn't sure what to put on some of the fields :O

stevenknight said at 2009-11-10 18:00:19

stevenknight => issues@scons

gregnoel said at 2010-01-20 02:20:51

Bug party triage. This area has been heavily revamped. Bill to research and see if the problem still happens.

John, can you try your test case with the newest checkpoint (published yesterday) and see if it's been fixed? Add a note to this issue and let us (well, Bill, to be precise) if you still see the problem. Tks.

gregnoel said at 2010-07-21 16:58:11

Bug party triage. Bump this issue to P1 so it will be reviewed at next bug party.

jchristian attached testpch.zip at 2008-11-04 00:39:53.

Zip file that creates the dir structure described in the defect

Activity

  1. added this to the milestone on Jan 2, 2018
  2. mwichmann commented on Apr 7, 2021

    @mwichmann
    Collaborator

    Tagged this with variantdir because that (in the old form BuildDir) appears in the SConscript.

  3. added
    pch
    and removed on Sep 28, 2021
  4. mwichmann commented on Nov 3, 2023

    @mwichmann
    Collaborator

    Something about this sounds familiar - wasn't there some ordering issue? #2877 has one of these.

  5. bdbaddog commented on Nov 4, 2023

    @bdbaddog
    ContributorAuthor

    The original filer is using glob.glob('*.cpp') which doesn't guarantee order staying the same between runs... That could have something to do with this..

  6. bdbaddog commented on Nov 4, 2023

    @bdbaddog
    ContributorAuthor

    The original filer is using glob.glob('*.cpp') which doesn't guarantee order staying the same between runs... That could have something to do with this..

    I've imported the zip file and updated for python3 and BuildDir->VariantDir change.
    Here: https://github.com/bdbaddog/scons-bugswork/tree/main/2249

    This also has the problem where the VariantDir()'s source is a parent of the variantdir..

    staticlibenv.VariantDir(builddir+"/static", ".", duplicate=0)

    With my updates and one more, it's not finding c.pch in static.

  7. bdbaddog commented on Nov 4, 2023

    @bdbaddog
    ContributorAuthor

    Not exactly sure what's the issue.

    Here's the generated command line which get's run (after my changes.. I moved variant_dir to the SConscript call so the variantdir wasn't a child of the src dir).
    When it gets run, it doesn't generated any files? (@jcbrill - any idea? I'm not the PCH expert by far)..

    cl /Fobuild\debug\lib\core\static\C.obj /c build\debug\lib\core\static\C.cpp /TP /nologo -Od -MDd -Ob0 -Z7 -W4 -EHsc -GR -D_DEBUG -DUSE_PCH -Yl__xge_pch_symbol /Iinclude /Yucore/CorePCH.hpp /Fpbuild\debug\lib\core\static\C.pch

    All my updates are available here: https://github.com/bdbaddog/scons-bugswork/tree/main/2249

  8. jcbrill commented on Nov 4, 2023

    @jcbrill
    Contributor

    When it gets run, it doesn't generated any files? (@jcbrill - any idea? I'm not the PCH expert by far)..

    I'm not either. When proceeding, keep in mind I'm just trying to help.

    The sample files do illustrate a problem though.

    Something about this sounds familiar - wasn't there some ordering issue? #2877 has one of these.

    There does appear to be a lexical ordering issue.

    All my updates are available here: https://github.com/bdbaddog/scons-bugswork/tree/main/2249

    Using a recent version of scons with the build files, I had to change one line in the SConscript file due to a "PCHSTOP construction variable must be a string" error.

    Original:

    staticlibenv2['PCHSTOP'] = File('core/CorePCH.hpp')
    

    Modified:

    staticlibenv2['PCHSTOP'] = str(File('core/CorePCH.hpp'))
    

    Working thesis: Any generated pch file name that is lexically ordered before "core" fails while any generated pch file name that is lexically ordered after "core" passes.

    File C.cpp (C.pch) is lexically ordered before core and fails.
    File Z.cpp (Z.pch) is lexically ordered after core and passes.

    The results from two builds with and environment dump and command-line options --taskmastertrace - --tree=all are included in the text files corD-fail.txt (source file corD.cpp) and corF-pass.txt. (source file corF.cpp).

    corD-fail.txt
    corF-pass.txt

    File corD-fail.txt contains the results when using corD.cpp for the file name (pch_nodes = staticlibenv2.PCH("corD.cpp"))
    File corF-fail.txt contains the results when using corF.cpp for the file name (pch_nodes = staticlibenv2.PCH("corF.cpp"))

    corD-fail.txt

    The tree for corD-fail.txt is:

    +-.
      +-build
      | +-build\debug
      |   +-build\debug\lib
      |     +-build\debug\lib\core
      |       +-build\debug\lib\core\static
      |         +-build\debug\lib\core\static\corD.cpp
      |         +-build\debug\lib\core\static\corD.obj
      |         | +-build\debug\lib\core\static\corD.cpp
      |         | +-include\core\CorePCH.hpp
      |         | +-include\core\Hello.hpp
      |         | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         +-build\debug\lib\core\static\corD.pch
      |         | +-build\debug\lib\core\static\corD.cpp
      |         | +-include\core\CorePCH.hpp
      |         | +-include\core\Hello.hpp
      |         | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         +-build\debug\lib\core\static\core
      |         | +-build\debug\lib\core\static\core\CorePCH.hpp
      |         +-build\debug\lib\core\static\core.lib
      |         | +-build\debug\lib\core\static\Hello.obj
      |         | | +-build\debug\lib\core\static\Hello.cpp
      |         | | +-build\debug\lib\core\static\corD.pch
      |         | | | +-build\debug\lib\core\static\corD.cpp
      |         | | | +-include\core\CorePCH.hpp
      |         | | | +-include\core\Hello.hpp
      |         | | | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         | | +-include\core\CorePCH.hpp
      |         | | +-include\core\Hello.hpp
      |         | | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         | +-build\debug\lib\core\static\corD.obj
      |         | | +-build\debug\lib\core\static\corD.cpp
      |         | | +-include\core\CorePCH.hpp
      |         | | +-include\core\Hello.hpp
      |         | | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\lib.EXE
      |         +-build\debug\lib\core\static\Hello.cpp
      |         +-build\debug\lib\core\static\Hello.obj
      |         | +-build\debug\lib\core\static\Hello.cpp
      |         | +-build\debug\lib\core\static\corD.pch
      |         | | +-build\debug\lib\core\static\corD.cpp
      |         | | +-include\core\CorePCH.hpp
      |         | | +-include\core\Hello.hpp
      |         | | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         | +-include\core\CorePCH.hpp
      |         | +-include\core\Hello.hpp
      |         | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         +-build\debug\lib\core\static\SConscript
      +-include
      | +-include\core
      |   +-include\core\CorePCH.hpp
      |   +-include\core\Hello.hpp
      +-lib
      | +-lib\core
      |   +-lib\core\corD.cpp
      |   +-lib\core\core
      |   | +-lib\core\core\CorePCH.hpp
      |   +-lib\core\Hello.cpp
      |   +-lib\core\SConscript
      +-SConstruct
    
    

    corF-pass.txt

    The tree for corF-pass.txt is:

    +-.
      +-build
      | +-build\debug
      |   +-build\debug\lib
      |     +-build\debug\lib\core
      |       +-build\debug\lib\core\static
      |         +-build\debug\lib\core\static\core
      |         | +-build\debug\lib\core\static\core\CorePCH.hpp
      |         +-build\debug\lib\core\static\core.lib
      |         | +-build\debug\lib\core\static\Hello.obj
      |         | | +-build\debug\lib\core\static\Hello.cpp
      |         | | +-build\debug\lib\core\static\corF.pch
      |         | | | +-build\debug\lib\core\static\corF.cpp
      |         | | | +-include\core\CorePCH.hpp
      |         | | | +-include\core\Hello.hpp
      |         | | | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         | | +-include\core\CorePCH.hpp
      |         | | +-include\core\Hello.hpp
      |         | | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         | +-build\debug\lib\core\static\corF.obj
      |         | | +-build\debug\lib\core\static\corF.cpp
      |         | | +-include\core\CorePCH.hpp
      |         | | +-include\core\Hello.hpp
      |         | | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\lib.EXE
      |         +-build\debug\lib\core\static\corF.cpp
      |         +-build\debug\lib\core\static\corF.obj
      |         | +-build\debug\lib\core\static\corF.cpp
      |         | +-include\core\CorePCH.hpp
      |         | +-include\core\Hello.hpp
      |         | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         +-build\debug\lib\core\static\corF.pch
      |         | +-build\debug\lib\core\static\corF.cpp
      |         | +-include\core\CorePCH.hpp
      |         | +-include\core\Hello.hpp
      |         | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         +-build\debug\lib\core\static\Hello.cpp
      |         +-build\debug\lib\core\static\Hello.obj
      |         | +-build\debug\lib\core\static\Hello.cpp
      |         | +-build\debug\lib\core\static\corF.pch
      |         | | +-build\debug\lib\core\static\corF.cpp
      |         | | +-include\core\CorePCH.hpp
      |         | | +-include\core\Hello.hpp
      |         | | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         | +-include\core\CorePCH.hpp
      |         | +-include\core\Hello.hpp
      |         | +-C:\Software\MSVS-2022-143-Com\VC\Tools\MSVC\14.37.32822\bin\HostX64\x64\cl.EXE
      |         +-build\debug\lib\core\static\SConscript
      +-include
      | +-include\core
      |   +-include\core\CorePCH.hpp
      |   +-include\core\Hello.hpp
      +-lib
      | +-lib\core
      |   +-lib\core\core
      |   | +-lib\core\core\CorePCH.hpp
      |   +-lib\core\corF.cpp
      |   +-lib\core\Hello.cpp
      |   +-lib\core\SConscript
      +-SConstruct
    

    Hope this points someone in the right direction.

    Edit: Does the lexical ordering issue indicate a potential dependency issue?

  9. 36 remaining items

  10. jcbrill commented on Nov 7, 2023

    @jcbrill
    Contributor

    Old but useful: https://stackoverflow.com/questions/35408988/lnk2011-why-does-link-exe-require-stub-obj-to-be-linked-alongside-precompiled-h

    I'm starting to wonder if there could be a problem when linking with created static library in another program since the pch object file is not included when building the static library. Any thoughts?

    I tested the modified example above to generate a SharedLibrary and it does in fact include the pch object file when linking.

  11. jcbrill commented on Nov 8, 2023

    @jcbrill
    Contributor

    @mwichmann and @bdbaddog PCH generation issue and possible code change solution explained.

    Description of terms used below:

    • PCH.cpp: pch source file used to produce the precompiled header binary and object file
    • PCH.pch: generated precompiled header binary
    • PCH.obj: generated object file for pch source file

    The mermaid diagrams are rendered when viewing the GitHub html page.

    Observed Behavior

    From above in this thread:

    There is an issue when both the environment PCH method is called and the pch source file is included in the source file list that can result in build failure.

    Summary:

    • When the pch source file is not in the source file list, the build is successful.
    • When the pch source file is in the source file list, the build may fail.

    The reason why the build may succeed in some configurations and fail in other configurations when the pch source file is in the source list is described in the next section.

    Issue Description and Illustration

    When both the environment PCH method is called and the pch source file is included in the source file list, the PCH.obj node has two builders/emitters assigned during construction with the second builder/emitter overwriting the original builder/emitter.

    This is undesirable as a taskmaster evaluation criteria has been removed and the lexical ordering of nodes affects the evaluation order during the DAG walk. The DAG walk and evaluation order is not deterministic. Builds that are successful, succeed for the wrong reason.

    SConscript fragment that results in State A and State B in the diagrams below (some build configurations may fail):

    # PCH_SRC is in srclist
    env.PCH(PCH_CPPFILE)
    env.StaticLibrary("core", source=srclist)
    

    SConscript fragment that results in State A, State B, and State C in the diagrams below (all build configurations pass):

    # PCH_SRC is in srclist
    env.PCH(PCH_CPPFILE)
    env.StaticLibrary("core", source=srclist)
    env.PCH(PCH_CPPFILE)
    

    The second call to the environment PCH method resolves the issue and is presented for exposition purposes only. However, the behavior informs the proposed solution below.

    Node PCH.pch and PCH.obj states:

    • State A: env.PCH('PCH.cpp')

      • msvc.pch_emitter(['PCH.pch'], ['PCH.cpp'])
      flowchart LR
        subgraph 1 ["State A: env.PCH('PCH.cpp') => msvc.pch_emitter"]
        direction LR
        N1[PCH.pch] --> B1["Builder $PCHCOMSTR"] --> E1["Executor $CXX ... <br> target=[PCH.pch, PCH.obj], source=[PCH.cpp]"]
        N2[PCH.obj] --> B1
        end
      
      Loading

      The environment PCH method causes the pch emitter to be assigned to both the PCH.pch and PCH.obj nodes.

      The first target for the PCH.pch and PCH.obj nodes is PCH.pch (e.g., target[0]==PCH.pch).

    • State B: StaticLibrary('core', source=['PCH.cpp', 'Hello.cpp'])

      • msvc.static_object_emitter(['PCH.obj'], ['PCH.cpp'])
      flowchart LR
        subgraph 2 ["State B: StaticLibrary('core', source=['PCH.cpp', 'Hello.cpp']) => msvc.static_object_emitter"]
        direction LR
        N3[PCH.pch] --> B2["Builder $PCHCOMSTR"] --> E2["Executor $CXX ... <br> target=[PCH.pch, PCH.obj], source=[PCH.cpp]"]
        N4[PCH.obj] --> B3["Builder CXXAction"] --> E3["Executor $CXX ... <br> target=[PCH.OBJ], source=[PCH.cpp]"]
        end
      
      Loading

      The environment StaticLibrary method causes the static object emitter to be assigned to the PCH.obj node.

      The first target for the PCH.obj node is now PCH.obj (e.g., target[0]==PCH.obj) and not PCH.pch.

      The target[0] change influences the DAG walk evaluation order and is the root cause of the build failures. However, even in the builds that succeed, they are really succeeding for the wrong reason.

      PCH.obj has lost it's primary target of PCH.pch when the builder/executor is overwritten.

      The target[0] change allows the PCH.obj node to be executed before the PCH.pch node is executed in some cases based on the lexical ordering of nodes.

      This is seen in the build failures for PCH.obj as the command issued is to use the pch file rather than create the pch file.

    • [Optional] State C: env.PCH('PCH.cpp')

      • msvc.pch_emitter(['PCH.pch'], ['PCH.cpp'])
      flowchart LR
        subgraph 3 ["State C: env.PCH('PCH.cpp') => msvc.pch_emitter"]
        direction LR
        N5[PCH.pch] --> B4["Builder $PCHCOMSTR"] --> E4["Executor $CXX ... <br> target=[PCH.pch, PCH.obj], source=[PCH.cpp]"]
        N6[PCH.obj] --> B4
        end
      
      Loading

      Calling the env PCH method a second time after the environment StaticLibrary call restores the builder/executor for PCH.obj.

      The first target for the PCH.pch and PCH.obj nodes is PCH.pch (e.g., target[0]==PCH.pch).

    Can the dual assignment of build/emitter to PCH.obj be prevented? The possible solution below appears to solve this problem.

    Possible Solution

    SCons.Tool.msvc.object_emitter:

    • Current code

      def object_emitter(target, source, env, parent_emitter):
          """Sets up the PCH dependencies for an object file."""
      
          validate_vars(env)
      
          parent_emitter(target, source, env)
      
          # Add a dependency, but only if the target (e.g. 'Source1.obj')
          # doesn't correspond to the pre-compiled header ('Source1.pch').
          # If the basenames match, then this was most likely caused by
          # someone adding the source file to both the env.PCH() and the
          # env.Program() calls, and adding the explicit dependency would
          # cause a cycle on the .pch file itself.
          #
          # See issue #2505 for a discussion of what to do if it turns
          # out this assumption causes trouble in the wild:
          # https://github.com/SCons/scons/issues/2505
          pch=get_pch_node(env, target, source)
          if pch:
              if str(target[0]) != SCons.Util.splitext(str(pch))[0] + '.obj':
                  env.Depends(target, pch)
      
          return (target, source)
      
    • Possible solution code (annotated):

      def object_emitter(target, source, env, parent_emitter):
          """Sets up the PCH dependencies for an object file."""
      
          validate_vars(env)
      
          parent_emitter(target, source, env)
      
          # Add a dependency, but only if the target (e.g. 'Source1.obj')
          # doesn't correspond to the pre-compiled header ('Source1.pch').
          # If the basenames match, then this was most likely caused by
          # someone adding the source file to both the env.PCH() and the
          # env.Program() calls, and adding the explicit dependency would
          # cause a cycle on the .pch file itself.
          #
          # See issue #2505 for a discussion of what to do if it turns
          # out this assumption causes trouble in the wild:
          # https://github.com/SCons/scons/issues/2505
          pch=get_pch_node(env, target, source)
          if pch:
              pch_basename = SCons.Util.splitext(str(pch))[0]  # <-- save the basename
              if str(target[0]) != pch_basename + '.obj':      # <-- use the basename
                  env.Depends(target, pch)
              elif str(source[0]) == pch_basename + '.cpp':    # <-- use the basename
                  # target == PCH.obj and source == PCH.cpp
                  # don't overwrite PCH builder for PCH.obj
                  target = None                                # <-- invalidate target list
                  source = None                                # <-- invalidate source list
      
          return (target, source)
      

      When the object_emitter is called for target PCH.obj and source PCH.cpp, the target list and source list is invalidated (i.e., both are set to None) which suppresses the assignment of the static object builder/emitter to the PCH.obj node (i.e., the pch builder/emitter is not overwritten).

      By maintaining the original pch builder/emitter assignment for PCH.obj, the DAG walk evaluation order is deterministic which is desirable.

      The PCH.pch node is executed before the PCH.obj node is executed.

    Manual test results for proposed code:

    Build Kind PCH.cpp Hellp.CPP Rem PCH.CPP Result First Node Output
    1 static a-pch.cpp b-hello.cpp False Pass a-pch.pch a-pch.pch, a-pch.obj
    2 shared a-pch.cpp b-hello.cpp False Pass a-pch.pch a-pch.pch, a-pch.obj
    3 static b-pch.cpp a-hello.cpp False Pass b-pch.pch b-pch.pch, b-pch.obj
    4 shared b-pch.cpp a-hello.cpp False Pass b-pch.pch b-pch.pch, b-pch.obj
    5 static a-pch.cpp b-hello.cpp True Pass a-pch.pch a-pch.pch, a-pch.obj
    6 shared a-pch.cpp b-hello.cpp True Pass a-pch.pch a-pch.pch, a-pch.obj
    7 static b-pch.cpp a-hello.cpp True Pass b-pch.pch b-pch.pch, b-pch.obj
    8 shared b-pch.cpp a-hello.cpp True Pass b-pch.pch b-pch.pch, b-pch.obj

    With the proposed code change:

    • All manual tests result in the PCH.pch node being evaluated first which produces the PCH.pch and PCH.obj files regardless of the PCH.pch name and any lexical ordering as the initial PCH.obj target list from the PCH builder/emitter is preserved.

    • The automated test scons/test/MSVC/PCH-source.py passes regardless of source file order.

    • The automated tests for MSVC/MSVC (79 tests) all pass or have no result.

  12. mwichmann commented on Nov 12, 2023

    @mwichmann
    Collaborator

    Sorry I haven't had a chance to really look at this in detail yet, but the analysis looks on point. I did put up a PR to the docs last week that suggested not including the "pch source file" as a source elsewhere, as SCons will track it correctly from there. I presume that's really not enough of a "solution"? The previously referenced issue #2505 did suggest limited confidence that the fix applied there was entirely correct, which has proven to be true, since this detail of dueling emitters was not recognized.

  13. jcbrill commented on Nov 21, 2023

    @jcbrill
    Contributor

    No worries.

    The proposed solution above was tweaked a little and is now available for testing in PR #4444.

    In limited testing, it appears to "do the right thing".

    The PR passes for the 16 combinations of the four pairs:

    • File name order: (a-pch.cpp, b-hello.cpp) vs (b-pch.cpp, a-hello.cpp)
    • PCH.cpp is in the source file list: True vs False
    • The env.PCH() call is before (or after) the StaticLibrary/SharedLibrary call: True vs False
    • Library kind: StaticLibrary vs SharedLibrary

    The PCH-source test was modified to have "foo.cpp" at the end of the list which used to fail.

    It might not be the worst idea to mention than there can only be one pch node per environment in addition to the requirement that the pch source file must be c++.

  14. mwichmann commented on Nov 21, 2023

    @mwichmann
    Collaborator

    Now that that's in a published version, I'm happy to receive concrete suggestions for improvement (which I will undoubtedly tweak further).... https://scons.org/doc/production/HTML/scons-man.html#b-PCH

  15. bdbaddog commented on Nov 30, 2023

    @bdbaddog
    ContributorAuthor

    @jcbrill - sorry for the delay in reviewing this and the PR.
    So your suggested solution is to fix this under the hood and just make it work?

    What happens if env['PCH'] is set, but the user never calls env.PCH(...) ?

  16. jcbrill commented on Nov 30, 2023

    @jcbrill
    Contributor

    sorry for the delay in reviewing this and the PR.

    No need to apologize. I'm sorry for going missing the last few days.

    So your suggested solution is to fix this under the hood and just make it work?

    Yes.

    What happens if env['PCH'] is set, but the user never calls env.PCH(...) ?

    That is a really good question.

    Without the env.PCH(...) call, the output pch file will not be generated and the build fails.

    In the current implementation, there are different reasons for the build failure based on whether or not the pch source file is removed from the source file list:

    • When the pch source file is in the source file list, there is a c compiler error.
    • When the pch source file is not in the source file list, there is an scons error.

    In the suggested solution, there is an scons error regardless of whether the pch source file is in the source file list or not:

    • When the pch source file is in the source file list, there is an scons error.
    • When the pch source file is not in the source file list, there is an scons error.

    One could argue that it is more desirable to fail with an scons error rather than a c compiler error.

    The results of the four runs are shown below based on the following combinations: (master, branch) x (pch source file included, pch source file removed).

    Test results:

    • master (scons-master)

      • pch source file included in source list: c compiler error

        fatal error C1083: Cannot open precompiled header file: 'build\debug\lib\core\static\a-pch.pch': No such file or directory

        scons: Reading SConscript files ...
        **** Compiling in debug mode...
        PCH_FILE_REMOVE = False
        scons: done reading SConscript files.
        scons: Building targets ...
        cl /Fobuild\debug\lib\core\static\a-pch.obj /c build\debug\lib\core\static\a-pch.cpp /TP /nologo -Od -MDd -Ob0 -Z7 -W4 -EHsc -GR -D_DEBUG -DUSE_PCH -Yl__xge_pch_symbol /Iinclude /Yucore/CorePCH.hpp /Fpbuild\debug\lib\core\static\a-pch.pch
        a-pch.cpp
        build\debug\lib\core\static\a-pch.cpp(1): fatal error C1083: Cannot open precompiled header file: 'build\debug\lib\core\static\a-pch.pch': No such file or directory
        scons: *** [build\debug\lib\core\static\a-pch.obj] Error 2
        scons: building terminated because of errors.
        
      • pch source file not in source list: scons error

        scons: *** [build\debug\lib\core\static\b-hello.obj] Explicit dependency 'build\debug\lib\core\static\a-pch.pch' not found, needed by target 'build\debug\lib\core\static\b-hello.obj'

        scons: Reading SConscript files ...
        **** Compiling in debug mode...
        PCH_FILE_REMOVE = True
        scons: done reading SConscript files.
        scons: Building targets ...
        scons: *** [build\debug\lib\core\static\b-hello.obj] Explicit dependency `build\debug\lib\core\static\a-pch.pch' not found, needed by target `build\debug\lib\core\static\b-hello.obj'.`
        scons: building terminated because of errors.
        
    • branch (jbrill-msvc-pchnode)

      • pch source file included in source list: scons error

        scons: *** [build\debug\lib\core\static\b-hello.obj] Explicit dependency 'build\debug\lib\core\static\a-pch.pch' not found, needed by target 'build\debug\lib\core\static\b-hello.obj'

        scons: Reading SConscript files ...
        **** Compiling in debug mode...
        PCH_FILE_REMOVE = False
        scons: done reading SConscript files.
        scons: Building targets ...
        scons: *** [build\debug\lib\core\static\b-hello.obj] Explicit dependency `build\debug\lib\core\static\a-pch.pch' not found, needed by target `build\debug\lib\core\static\b-hello.obj'.
        scons: building terminated because of errors.
        
      • pch source file not included in source list: scons error

        scons: *** [build\debug\lib\core\static\b-hello.obj] Explicit dependency 'build\debug\lib\core\static\a-pch.pch' not found, needed by target 'build\debug\lib\core\static\b-hello.obj'

        scons: Reading SConscript files ...
        **** Compiling in debug mode...
        PCH_FILE_REMOVE = True
        scons: done reading SConscript files.
        scons: Building targets ...
        scons: *** [build\debug\lib\core\static\b-hello.obj] Explicit dependency `build\debug\lib\core\static\a-pch.pch' not found, needed by target `build\debug\lib\core\static\b-hello.obj'.
        scons: building terminated because of errors.
        

    EDIT: ADDENDUM

    In the current implementation, the names of the source files matter.

    In the case above (a-pch.pch, b-hello.cpp) there are different errors.

    For (b-pch.cpp, a-hello.cpp), there is only the scons dependency error.

    In the suggested solution, the same error is produced regardless of source file naming.

  17. mwichmann commented on Nov 30, 2023

    @mwichmann
    Collaborator

    What happens if env['PCH'] is set, but the user never calls env.PCH(...) ?

    Well, in this case (rephrasing from the previous comment) - you haven't given SCons the information of how a PCH file fits into the plumbing, so it shouldn't be expected to work. If the implementation were different, it might theoretically work if the PCH file were already present in the source tree, SCons just wouldn't know how to regenerate it, but since Microsoft also requires the "PCH object file" (don't even know what to call that) to be part of the link, it can't work. I guess one could ask - should env['PCH'] even have any meaning if env.PCH() hasn't been called, and just get ignored? But we don't have to solve every detail...

  18. bdbaddog commented on Nov 30, 2023

    @bdbaddog
    ContributorAuthor

    What happens if env['PCH'] is set, but the user never calls env.PCH(...) ?

    Well, in this case (rephrasing from the previous comment) - you haven't given SCons the information of how a PCH file fits into the plumbing, so it shouldn't be expected to work. If the implementation were different, it might theoretically work if the PCH file were already present in the source tree, SCons just wouldn't know how to regenerate it, but since Microsoft also requires the "PCH object file" (don't even know what to call that) to be part of the link, it can't work. I guess one could ask - should env['PCH'] even have any meaning if env.PCH() hasn't been called, and just get ignored? But we don't have to solve every detail...

    It might be dumb, but the no PCH() should work. the pch.cpp file would basically be a no-op right?

  19. mwichmann commented on Nov 30, 2023

    @mwichmann
    Collaborator

    I get more confused the more time passes. We do this in various tests, so we're setting both (as you'd expect).

    env['PCH'] = env.PCH('Precompiled.cpp')[0]

    Meanwhile, there's a routine get_pch_node that basically fishes out the node for PCH, and mslink uses that to deduce the object file name and add it to the dllEmitter and progEmitter, so I think it's not a no-op.

  20. jcbrill commented on Nov 30, 2023

    @jcbrill
    Contributor

    Meanwhile, there's a routine get_pch_node that basically fishes out the node for PCH, and mslink uses that to deduce the object file name and add it to the dllEmitter and progEmitter, so I think it's not a no-op.

    This. msvc also calls get_pch_node in the object emitter.

    Once the pch node has been defined, the compile commands will include the pch header in the command-line (e.g., /Yucore/CorePCH.hpp ) which would fail if there was not an explicit dependency error.

    I'm not sure there is a reliable way to know if env.PCH() has been called and when it was called (before or after the env['PCH'] assignment).

  21. mwichmann commented on Nov 30, 2023

    @mwichmann
    Collaborator

    I wonder if the idea is to say not to set the PCH consvar manually, and instead have the PCH builder be the one that sets it.

  22. jcbrill commented on Nov 30, 2023

    @jcbrill
    Contributor

    It appears that calling env.PCH() and not defining env['PCH'] fails with a python error (at least in the suggested version).

    However, there is a non-trivial chance that the test configuration is completely messed up.

    I don't have time to investigate further tonight, but will tomorrow morning.

  23. jcbrill commented on Dec 1, 2023

    @jcbrill
    Contributor

    I wonder if the idea is to say not to set the PCH consvar manually, and instead have the PCH builder be the one that sets it.

    The suggested solution was adjusted to set env['PCH']=pch in the msvc pch_emitter when either env['PCH'] is undefined or evaluates to false.

    A set of 24 experiments were run using the 4.6.0ish main branch and the suggested solution jbrill-msvc-pchnode. The results of the experiments are shown below.

    Comments:

    • calling env.PCH() without setting env['PCH'] results in python errors in the current implementation in some cases. The taskmaster eventually tries to call a node's executor method when the node's executor is None.
    • setting env['PCH'] without calling env.PCH() results in c errors and scons errors in the current implementation.
    • setting env['PCH'] without calling env.PCH() results in scons errors in the currrent suggested implementation.

    At present, I'm not sure that setting env['PCH'] without calling env.PCH() can be turned into a no-op.

    Experiment Results

    Column legend for tables:

    • pchsrch (pch source file):
      • a-pch: a-pch.cpp, b-hello.cpp
      • b-pch: b-pch.cpp, a-hello.cpp
    • remsrc (remove pch source file from source file list):
      • False: pch source file is in source file list
      • True: pch source file is not in source file list
    • pchcall (call env.PCH()):
      • False: do not call env.PCH()
      • True: call env.PCH()
    • before (call env.PCH() before env['PCH'] assignment, if any):
      • n/a: does not apply, env.PCH() not called
      • False: env.PCH() is called after env['PCH'] assignment, if any
      • True: env.PCH() is called before env['PCH'] assignment, if any
    • envpch (assign env['PCH']):
      • False: do not assign env['PCH']
      • True: assign env['PCH']

    NOTE: Pass does not mean that precompiled headers are being used, simple that the library build successfully.

    Branch 4.6.0 (total: 24, fail c: 3, fail python: 4, fail scons: 3, pass: 14):

    id pchsrc remsrc pchcall before envpch result
    1 a-pch False False n/a False Pass
    2 a-pch False False n/a True Fail: C1083: Cannot open precompiled header file
    3 a-pch False True False False Fail: AttributeError: 'NoneType' object has no attribute 'get_build_env'
    4 a-pch False True False True Fail: C1083: Cannot open precompiled header file
    5 a-pch False True True False Fail: AttributeError: 'NoneType' object has no attribute 'get_build_env'
    6 a-pch False True True True Fail: C1083: Cannot open precompiled header file
    7 a-pch True False n/a False Pass
    8 a-pch True False n/a True Fail: Explicit dependency
    9 a-pch True True False False Pass
    10 a-pch True True False True Pass
    11 a-pch True True True False Pass
    12 a-pch True True True True Pass
    13 b-pch False False n/a False Pass
    14 b-pch False False n/a True Fail: Explicit dependency
    15 b-pch False True False False Fail: AttributeError: 'NoneType' object has no attribute 'get_build_env'
    16 b-pch False True False True Pass
    17 b-pch False True True False Fail: AttributeError: 'NoneType' object has no attribute 'get_build_env':
    18 b-pch False True True True Pass
    19 b-pch True False n/a False Pass
    20 b-pch True False n/a True Fail: Explicit dependency
    21 b-pch True True False False Pass
    22 b-pch True True False True Pass
    23 b-pch True True True False Pass
    24 b-pch True True True True Pass

    Branch jbrill-msvc-pchnode (total: 24, fail c: 0, fail python: 0, fail scons: 4, pass: 20):

    id pchsrc remsrc pchcall before envpch result
    1 a-pch False False n/a False Pass
    2 a-pch False False n/a True Fail: Explicit dependency
    3 a-pch False True False False Pass
    4 a-pch False True False True Pass
    5 a-pch False True True False Pass
    6 a-pch False True True True Pass
    7 a-pch True False n/a False Pass
    8 a-pch True False n/a True Fail: Explicit dependency
    9 a-pch True True False False Pass
    10 a-pch True True False True Pass
    11 a-pch True True True False Pass
    12 a-pch True True True True Pass
    13 b-pch False False n/a False Pass
    14 b-pch False False n/a True Fail: Explicit dependency
    15 b-pch False True False False Pass
    16 b-pch False True False True Pass
    17 b-pch False True True False Pass
    18 b-pch False True True True Pass
    19 b-pch True False n/a False Pass
    20 b-pch True False n/a True Fail: Explicit dependency
    21 b-pch True True False False Pass
    22 b-pch True True False True Pass
    23 b-pch True True True False Pass
    24 b-pch True True True True Pass

    Edits:

    • fixed error in comments above (3rd item: current changed to suggested)
  24. mwichmann commented on Nov 20, 2026

    @mwichmann
    Collaborator

    My inclination now is to close this issue citing unsupported usage, and add some small doc notes to clarify things to do/not do. Meanwhile, if people think it's useful (I'll wait for @jcbrill and @bdbaddog at least), open a new issue to track the more specific problem that the now-abandoned #4444 was after (prevent overwriting the PCH node), so we don't lose track of that real issue, but it's more focused than "wait, what, it matters what the PCH source file is named???"

    There are a lot of complex pieces that lead to the result we see, which is a true headscratcher - why would it matter what letter the filename starts with? At the very deepest level, the problem is that the thing we care about isn't in the dependency graph, so instead of picking the right dep from the graph, we go searching through a filesystem listing, and those are explicitly sorted to ensure repeatabilty. How we get there... much of it is in the material above so I won't attempt a rehash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions