You're encountering a common issue in Emacs org-mode with Babel code blocks: variables defined in one block are not automatically available in other blocks, even when using :noweb references. Each code block is executed in its own process/environment by default, so variables are not shared.
Here are several ways to share variables across org-babel code blocks:
1. Use :var Header Argument
You can pass variables explicitly to a block using the :var header argument.
Example:
#+name: var-block
#+begin_src emacs-lisp
(setq my-var 42)
#+end_src
#+name: use-var
#+begin_src emacs-lisp :var x=42
(message "x is %s" x)
#+end_src
Or, if you want to use the result of another block:
#+name: get-var
#+begin_src emacs-lisp
42
#+end_src
#+name: use-var
#+begin_src emacs-lisp :var x=get-var()
(message "x is %s" x)
#+end_src
2. Use :noweb with Variable Definitions
If you want to use :noweb to insert code, you need to ensure the variable is defined in the code, not just in the environment.
Example:
#+name: define-var
#+begin_src emacs-lisp
(setq my-var 42)
#+end_src
#+name: use-var
#+begin_src emacs-lisp :noweb yes
<<define-var>>
(message "my-var is %s" my-var)
#+end_src
But note: this will only work if the code from define-var is inserted into use-var at execution time. If you want the variable to persist across blocks, you must define it in a way that is visible to all blocks (e.g., as a global variable in Emacs Lisp).
3. Use Session Support
For languages that support sessions (like Python, R, Emacs Lisp), you can use the :session header argument to run blocks in the same process, so variables persist.
Example (Emacs Lisp):
#+begin_src emacs-lisp :session mysession
(setq my-var 42)
#+end_src
#+begin_src emacs-lisp :session mysession
(message "my-var is %s" my-var)
#+end_src
Example (Python):
#+begin_src python :session mysession
x = 42
#+end_src
#+begin_src python :session mysession
print(f"x is {x}")
#+end_src
4. Use Org Properties or Global Variables
For Emacs Lisp, you can define a global variable in your init file or at the top of your org file, and all blocks can access it.
Summary Table
| Method | How to Use | Languages Supported | Notes |
|---|
:var | Pass as header argument | All | Explicit, per block |
:noweb | Insert code | All | Code is inserted, not shared |
:session | Share process | Python, R, Emacs Lisp | Variables persist |
| Global vars | Define globally | Emacs Lisp | All blocks can access |
Recommendation
- For Emacs Lisp, use
:session or define global variables.
- For Python/R, use
:session.
- For other languages, use
:var to pass variables explicitly.
If you provide your language and a code example, I can give you a more tailored solution!